rspec/rules/S2204/java/rule.adoc

65 lines
2.0 KiB
Plaintext

== Why is this an issue?
The `equals` method in `AtomicInteger` and `AtomicLong` returns `true` only if two instances are identical, not if they represent the same number value.
This is because `equals` is not part of the API contract of these classes, and they do not override the method inherited from `java.lang.Object`.
Although both classes implement the `Number` interface, assertions about `equals` comparing number values are not part of that interface either.
Only the API contract of implementing classes like `Integer`, `Long`, `Float`, `BigInteger`, etc., provides such assertions.
== How to fix it
- To compare the number value of two instances `a` and `b` of `AtomicInteger` or `AtomicLong`, use `a.get() == b.get()` instead of `a.equals(b)`.
- If you want to check for object identity, use `a == b` instead of `a.equals(b)` to clarify your intention.
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
Boolean isSameNumberValue(AtomicLong a, AtomicLong b) {
return a.equals(b); // Noncompliant, this is true only if a == b
}
Boolean isSameReference(AtomicLong a, AtomicLong b) {
return a.equals(b); // Noncompliant, because misleading
}
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
Boolean isSameNumberValue(AtomicLong a, AtomicLong b) {
return a.get() == b.get(); // Compliant
}
Boolean isSameReference(AtomicLong a, AtomicLong b) {
return a == b; // Compliant
}
----
== Resources
=== Documentation
* https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/package-summary.html[Java SE 8 API Specification: Package "java.util.concurrent.atomic"]
=== Articles & blog posts
* https://programming.guide/java/atomicinteger-equals.html[Programming.Guide: AtomicInteger and equals / Comparable]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Use ".get()" to retrieve the value and compare it instead.
endif::env-github,rspecator-view[]