...
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
.
Noncompliant Code Example
This noncompliant code example declares enum Hydrocarbon
and uses its ordinal()
method to provide the result of the getNumberOfCarbons()
method.
...
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, 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; } } |
Risk Assessment
Use of ordinals to derive integer values reduces the program's maintainability and can lead to errors in the program.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
DCL04-J | low | probable | medium | P4 | L3 |
Related Guidelines
INT09-CPP. Ensure enumeration constants map to unique values | ||||
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="2f8fe15d3c49407a-a05be496-41fe47a5-8f8394c9-0ec3eae9894580da69d18745"><ac:plain-text-body><![CDATA[ | [ISO/IEC TR 24772:2010 | http://www.aitcnet.org/isai/] | "Enumerator Issues [java:CCB]" | ]]></ac:plain-text-body></ac:structured-macro> |
Bibliography
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="bf2998b2f4cc6f66-6c28e1e8-460a4c1d-a4cda809-7a9445f97481486483d9158e"><ac:plain-text-body><![CDATA[ | [java:[JLS 2005 | AA. Bibliography#JLS 05]] | [§8.9, "Enums" | http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.9] | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="594336f410694e60-d3d3689b-43c04858-be1f87e8-95676a6a23adfcc9cc4abb5d"><ac:plain-text-body><![CDATA[ | [java:[API 2006 | AA. Bibliography#API 06]] | [Enum | http://download.oracle.com/javase/6/docs/api/java/lang/Enum.html] | ]]></ac:plain-text-body></ac:structured-macro> |
...