Java Reference
In-Depth Information
enum Hydrocarbon {
METHANE, ETHANE, PROPANE, BUTANE, PENTANE,
HEXANE, HEPTANE, OCTANE, NONANE, DECANE;
public int getNumberOfCarbons() {
return ordinal() + 1;
}
}
Although this noncompliant code example behaves as expected, its maintenance is
likely to be problematic. If the
enum
constants were reordered, the
getNumberOfCar-
bons()
methodwouldreturnincorrectvalues.Furthermore,addinganadditional
BENZENE
constant to the model would break the invariant assumed by the
getNumberOfCarbons()
method, because benzene has six carbons, but the ordinal value six is already taken by
hexane.
Compliant Solution
Inthiscompliantsolution,
enum
constantsareexplicitlyassociatedwiththecorresponding
integer values for the number of carbon atoms they contain:
enum Hydrocarbon {
METHANE(1), ETHANE(2), PROPANE(3), BUTANE(4), PENTANE(5),
HEXANE(6), BENZENE(6), HEPTANE(7), OCTANE(8), NONANE(9),
DECANE(10);
private final int numberOfCarbons;
Hydrocarbon(int carbons) { this.numberOfCarbons = carbons; }
public int getNumberOfCarbons() {
return numberOfCarbons;
}
}
The
getNumberOfCarbons()
method no longer uses the
ordinal()
to discover the
number of carbon atoms for each value. Different
enum
constants may be associated with
the same value, as shown for
HEXANE
and
BENZENE
. Furthermore, this solution lacks any
dependence on the order of the enumeration; the
getNumberOfCarbons()
method would
continue to work correctly even if the enumeration were reordered.