Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Reworded some things; make the code examples more parallel

...

Wiki Markup
Section [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. However, Using the The {{ordinal()}} method torelies deriveon the valueplacement associated withof an enum constant isin errorthe pronelist and(which should be avoidedmay 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.

Wiki Markup
According to the Java API \[[API 2006|AA. Bibliography#API 06]\], {{ordinal()}} is defined as

...

Code Block
bgColor#FFcccc
enum HydroCarbon {
  METHANE, ETHANE, PROPANE, BUTANE, PENTANE,
  HEXANE, HEPTANE, OCTANE, NONANE, DECANE;

  public int getNumberOfCarbons() {
    return ordinal() + 1;
  }
}
public class TestHC {
  public static void main(String args[]) {
    /* ... */
    HydroCarbon hc = HydroCarbon.HEXANE;
    int index = hc.getNumberOfCarbons();
    int noHyd = NumberOfHydrogen[index]; // Can cause ArrayIndexOutOfBoundsException
  }
}

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.

...

Code Block
bgColor#ccccff
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;
  }
}

In this example, it is easy 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.

...