rspec/rules/S1201/java/rule.adoc
ADarko22 6e4bc94336
Modify rule S1201: Update rule according to the LayC (#2006)
Co-authored-by: Irina Batinic <irina.batinic@sonarsource.com>
2023-06-01 15:44:26 +02:00

100 lines
2.5 KiB
Plaintext

== Why is this an issue?
In Java, the `Object.equals()` method is used for object comparison, and it is typically overridden in classes
to provide a custom equality check based on your criteria for equality.
The default implementation of `equals()` provided by the `Object` class compares the memory references of the two objects,
that means it checks if the objects are actually the same instance in memory.
The "equals" as a method name should be used exclusively to override `Object.equals(Object)` to prevent confusion.
It is important to note that when you override `equals()`, you should also override the `hashCode()`
method to maintain the contract between `equals()` and `hashCode()`.
== How to fix it
Either override `Object.equals(Object)` or rename the method.
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
class MyClass {
private int foo = 1;
public boolean equals(MyClass o) { // Noncompliant; does not override Object.equals(Object)
return o != null && o.foo == this.foo;
}
public static void main(String[] args) {
MyClass o1 = new MyClass();
Object o2 = new MyClass();
System.out.println(o1.equals(o2)); // Prints "false" because o2 an Object not a MyClass
}
}
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
class MyClass {
private int foo = 1;
@Override
public boolean equals(Object o) { // Compliant
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MyClass other = (MyClass)o;
return this.foo == other.foo;
}
}
----
== Resources
=== Documentation
* https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/lang/Object.html#equals(java.lang.Object)[Oracle SDK - Object.equals(Object)]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Either override Object.equals(Object), or totally rename the method to prevent any confusion.
'''
== Comments And Links
(visible only on this page)
=== is related to: S3974
=== is related to: S1221
=== is related to: S2953
=== on 20 Aug 2013, 13:50:07 Freddy Mallet wrote:
Is implemented by \http://jira.codehaus.org/browse/SONARJAVA-300
=== on 24 Apr 2017, 10:46:16 Tibor Blenessy wrote:
I updated compliant example to not use ``++instanceof++`` operator, because that would reported as violation of RSPEC-2162
endif::env-github,rspecator-view[]