Java language enumeration types have an ordinal()
method that returns the numerical position of each enumeration constant in its class declaration.
The Java Language Specification [JLS 2005] §8.9, "Enums," does not specify the use of ordinal()
in programs. However, using the ordinal()
method to derive the value associated with an enum
constant is error prone and should be avoided.
According to the Java API [API 20062011], Class Enum<E extends Enum<E>> public final int ordinal()
:
Returns the ordinal of the enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero). Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data structures, such as
EnumSet
andEnumMap
.
The Java Language Specification [JLS 2011] §8.9, "Enums" does not specify the use of ordinal()
in programs. However, using the ordinal()
method to derive the value associated with an enum
constant is error prone and should be avoided.
Noncompliant Code Example
...
Although this noncompliant code example works, its maintenance is susceptible likely to vulnerabilitiesbe problematic. If the enum
constants were reordered, the getNumberOfCarbon()
method would return incorrect values. Also, BENZENE
— which also has 6 carbons — cannot be added without violating the current enum
design.
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), 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.
...
Guideline
...
Severity
...
Likelihood
...
Remediation Cost
...
Priority
...
Level
...
DCL58-JG
...
low
...
probable
...
medium
...
P4
...
Related Guidelines
ISO/IEC TR 24772:2010: "Enumerator Issues [CCB]"
Bibliography
[API 2006] |
DCL60-JG. Enable compile-time type checking of varargs types 01. Declarations and Initialization (DCL) DCL02-J. Declare all enhanced for statement loop variables final
...