Java language enumeration types have an ordinal() method, which returns the numerical position of each enumeration constant in its class declaration.
| Wiki Markup |
|---|
Section [8§8.9, "Enums"|http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.9] of the _Java Language Specification_ \[[JLS 2005|AA. Bibliography#JLS 05]\] does not specify the use of {{ordinal()}} in programs. The However, using the {{ordinal()}} method reliesto onderive the value placementassociated ofwith an enum constant inis theerror-prone listand (whichshould may be altered in the future due to insertions or deletions) rather than on an inherent property of the constant. Instead, use the rich enum features of Java to associate properties with each enum constant.be avoided. |
| Wiki Markup |
|---|
According to the Java API \[[API 2006|AA. Bibliography#API 06]\], {{ordinal()}} is defined as |
...
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
EnumSetandEnumMap.
Noncompliant Code Example
...
While this noncompliant code example works, its maintenance is susceptible to vulnerabilities. If the enum constants were reordered, the getNumberOfCarbon() method would return incorrect values. Also the current enum design can not accommodate the addition of BENZENE, , 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;
}
}
|
In this example, it is trivial to add BENZENE(6) to the list of constants with no fear of errors.
Risk Assessment
Use of ordinals to derive integer values reduces the program's maintainability and can lead to errors in the program.
...
C++ Secure Coding Standard: INT09-CPP. Ensure enumeration constants map to unique values
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this guideline on the CERT website.
Bibliography
| Wiki Markup |
|---|
\[[JLS 2005|AA. Bibliography#JLS 05]\] Section 8§8.9, "Enums" \[[API 2006|AA. Bibliography#API 06]\] [Enum|http://download.oracle.com/javase/6/docs/api/java/lang/Enum.html] |
...