rspec/rules/S4551/java/rule.adoc

64 lines
1.7 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
Testing equality of an enum value with ``++equals++`` is perfectly valid because an enum is an Object and every Java developer knows "==" should not be used to compare the content of an Object. At the same time, using "==" on enums:
* provides the same expected comparison (content) as ``++equals++``
* is more null-safe than equals()
* provides compile-time (static) checking rather than runtime checking
For these reasons, use of "==" should be preferred to ``++equals++``.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
public enum Fruit {
APPLE, BANANA, GRAPE
}
public enum Cake {
LEMON_TART, CHEESE_CAKE
}
public boolean isFruitGrape(Fruit candidateFruit) {
return candidateFruit.equals(Fruit.GRAPE); // Noncompliant; this will raise an NPE if candidateFruit is NULL
}
public boolean isFruitGrape(Cake candidateFruit) {
return candidateFruit.equals(Fruit.GRAPE); // Noncompliant; always returns false
}
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
public boolean isFruitGrape(Fruit candidateFruit) {
return candidateFruit == Fruit.GRAPE; // Compliant; there is only one instance of Fruit.GRAPE - if candidateFruit is a GRAPE it will have the same reference as Fruit.GRAPE
}
public boolean isFruitGrape(Cake candidateFruit) {
return candidateFruit == Fruit.GRAPE; // Compliant; compilation time failure
}
----
== Resources
2021-04-28 16:49:39 +02:00
* https://www.javaworld.com/article/2074292/core-java/use-----or-----to-compare-java-enums.html[Use ++==++ (or !=) to Compare Java Enums]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
include::highlighting.adoc[]
endif::env-github,rspecator-view[]