...
The Java Language Specification, §8.9, "Enums" [JLS 2011], 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.
Noncompliant Code Example
This noncompliant code example declares enum Hydrocarbon
and uses its ordinal()
method to provide the result of the getNumberOfCarbons()
method:
...
Although this noncompliant code example works as written, its maintenance is likely to be problematic. If the enum
constants were reordered, the getNumberOfCarbon()
method would return incorrect values. Furthermore, adding an additional BENZENE
constant to the model would break the invariant assumed by the getNumberOfCarbon()
method; benzene has 6 carbons, but the ordinal value 6 is already taken by 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:
...
Consequently, the getNumberOfCarbon()
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 getNumberOfCarbon()
method would continue to work even if the enumeration were reordered.
Applicability
It is acceptable to use the ordinals associated with an enumerated type when the order of the enumeration constants is standard and extra constants cannot be added. For example, the use of ordinals is permitted with the following enumerated type:
...
However, in general, use of ordinals to derive integer values reduces the program's maintainability and can lead to errors in the program.
Bibliography
[API 2011] | |
[Bloch 2008] | Item 31, "Use Instance Fields Instead of Ordinals" |
[JLS 2011] | §8.9, "Enums" |
...