45 lines
1.1 KiB
Plaintext
45 lines
1.1 KiB
Plaintext
The use of the ``++enum.ordinal()++`` method is regarded as suspicious since conceptually, the significance of an ``++enum++`` member is in what it represents, not its position within the ``++enum++``.
|
|
|
|
|
|
According to the method's Javadoc:
|
|
|
|
____
|
|
Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data structures, such as ``++EnumSet++`` and ``++EnumMap++``.
|
|
____
|
|
|
|
|
|
Further, reliance on a particular member's position within an ``++enum++`` is a bug waiting to happen since the position of members within an ``++enum++`` is not generally regarded as significant, and maintainers are just as likely to add new members at the beginning as at the end.
|
|
|
|
|
|
Therefore this rule raises an issue for each use of the ``++ordinal++`` method.
|
|
|
|
== Noncompliant Code Example
|
|
|
|
----
|
|
public enum Fruit {
|
|
APPLE, ORANGE, PLUM, GRAPE;
|
|
}
|
|
|
|
public void doTheThing(Fruit fruit) {
|
|
|
|
if (fruit.ordinal() == 2) { // Noncompliant
|
|
// ...
|
|
}
|
|
}
|
|
----
|
|
|
|
== Compliant Solution
|
|
|
|
----
|
|
public enum Fruit {
|
|
APPLE, ORANGE, PLUM, GRAPE;
|
|
}
|
|
|
|
public void doTheThing(Fruit fruit) {
|
|
|
|
if (Fruit.PLUM.equals(fruit)) {
|
|
// ...
|
|
}
|
|
}
|
|
----
|