...
The Java Language Specification [JLS 2011] §8.9, "Enums" does not specify the use of ordinal()
in programs. However, using attaching external significance to the ordinal()
method to derive the value associated with an value of an enum
constant is error prone and should be avoided.
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 currently works, its maintenance is likely to be problematic. If the enum
constants were reordered, the getNumberOfCarbon()
method would return incorrect values. Furthermore an additional BENZENE
constant could not be added to the model because it has 6 carbons, but the ordinal value 6 is already taken.
Compliant Solution
In this compliant solution, enum
constants are explicitly associated with the corresponding integer values for the number of carbon atoms they contain. Thus, the ordinal()
method is no longer involved required in knowing the number of carbon atoms for each value.
Code Block | ||
---|---|---|
| ||
enum Hydrocarbon { METHANE(1), ETHANE(2), PROPANE(3), BUTANE(4), PENTANE(5), HEXANE(6), HEPTANE(7), OCTANE(8), NONANE(9), DECANE(10); private final int numberOfCarbons; Hydrocarbon(int carbons) { this.numberOfCarbons = carbons; } public int getNumberOfCarbons() { return numberOfCarbons; } } |
Applicability
Use of ordinals to derive integer values reduces the program's maintainability and can lead to errors in the program.
Related Guidelines
ISO/IEC TR 24772:2010: "Enumerator Issues [CCB]"
Bibliography
...