Transilvania JUG

Sponsors

17
Sep
2014
5

Ensuring the numeric values of Enum constants

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++;
	}
}

5 Responses to Ensuring the numeric values of Enum constants

Leave a Reply

Your email address will not be published. Required fields are marked *

df