...
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
— the current enum design can not accommodate the addition of 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 easy trivial to add BENZENE(6) to the list of constants with no fear of errors.
...