...
The Java Language Specification, §8.9, "Enums" [JLS 20112013], does not specify the use of ordinal()
in programs. However, attaching external significance to the ordinal()
value of an enum
constant is error prone and should be avoided for defensive programming.
...
Although this noncompliant code example works behaves as writtenexpected, its maintenance is likely to be problematic. If the enum
constants were reordered, the getNumberOfCarbongetNumberOfCarbons()
method would return incorrect values. Furthermore, adding an additional BENZENE
constant to the model would break the invariant assumed by the getNumberOfCarbongetNumberOfCarbons()
method ; because benzene has 6 six carbons, but the ordinal value 6 is already taken by hexane HEXANE
.
Compliant Solution
In this compliant solution, enum
constants are explicitly associated with the corresponding integer values for the number of carbon atoms they contain:
Code Block | ||
---|---|---|
| ||
enum Hydrocarbon { METHANE(1), ETHANE(2), PROPANE(3), BUTANE(4), PENTANE(5), HEXANE(6), BENZENE(6), HEPTANE(7), OCTANE(8), NONANE(9), DECANE(10); private final int numberOfCarbons; Hydrocarbon(int carbons) { this.numberOfCarbons = carbons; } public int getNumberOfCarbons() { return numberOfCarbons; } } |
Consequently, the getNumberOfCarbonThe getNumberOfCarbons()
method no longer uses the ordinal()
to discover the number of carbon atoms for each value. Different enum
constants may be associated with the same value, as shown for HEXANE
and BENZENE
. Furthermore, this solution lacks any dependence on the order of the enumeration; the getNumberOfCarbonthe getNumberOfCarbons()
method method would continue to work even if the enumeration were reordered.
...
Code Block |
---|
public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } |
However, in In general, use of ordinals to derive integer values reduces the program's maintainability and can lead to errors in the program.
Bibliography
[Bloch 2008] | Item 31, "Use Instance Fields Instead of Ordinals" |
[JLS 20112013] | §8.9, "Enums" |
...