Over a million developers have joined DZone.

Ensuring the Numeric Values of Enum Constants

· Java Zone

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

Problem statement: you have an Enum and you want to ensure that the numeric values returned by ordinal are a certain way (perhaps this Enum is part of a communication protocol with an external system or perhaps it is written to a DB using an ORM).

One solution would be to write a unit test like the following:

@Test
public void testEnum() {
	Map<TestEnum, Integer> expectedValues = new EnumMap<TestEnum, Integer>(TestEnum.class);
	expectedValues.put(TestEnum.FOO, 0);
	expectedValues.put(TestEnum.BAR, 1);
	expectedValues.put(TestEnum.BAZ, 2);

	assertEquals(TestEnum.values().length, expectedValues.size());
	for (Map.Entry<TestEnum, Integer> entry: expectedValues.entrySet()) {
		assertEquals(entry.getKey().ordinal(), entry.getValue().intValue());
	}
}

Of course this presupposes that the unittests are run frequently to catch any possible errors. Alternatively we can implement our Enum as shown below, which will check the values during load time (and prevent the loading of the enum by the classloader – by virtue of throwing an exception during the initialization phase – if the values are incorrect):

public enum TestEnum {
	FOO(0), BAR(1), BAZ(2);

	private static class CounterHolder {
		static int COUNTER = 0;
	}

	TestEnum(int order) {
		if (order != CounterHolder.COUNTER) {
			throw new IllegalArgumentException("Expected "
					+ CounterHolder.COUNTER + " but was " + order);
		}
		CounterHolder.COUNTER++;
	}
}

Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.

Topics:

Published at DZone with permission of Attila-Mihaly Balazs, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}