67 lines
1.4 KiB
Plaintext
67 lines
1.4 KiB
Plaintext
== Why is this an issue?
|
|
|
|
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
|
|
|
|
[source,java]
|
|
----
|
|
public enum Fruit {
|
|
APPLE, ORANGE, PLUM, GRAPE;
|
|
}
|
|
|
|
public void doTheThing(Fruit fruit) {
|
|
|
|
if (fruit.ordinal() == 2) { // Noncompliant
|
|
// ...
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,java]
|
|
----
|
|
public enum Fruit {
|
|
APPLE, ORANGE, PLUM, GRAPE;
|
|
}
|
|
|
|
public void doTheThing(Fruit fruit) {
|
|
|
|
if (Fruit.PLUM.equals(fruit)) {
|
|
// ...
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::message.adoc[]
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::comments-and-links.adoc[]
|
|
endif::env-github,rspecator-view[]
|