rspec/rules/S1201/java/rule.adoc

103 lines
2.1 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
"equals" as a method name should be used exclusively to override ``++Object.equals(Object)++`` to prevent any confusion.
It is tempting to overload the method to take a specific class instead of ``++Object++`` as parameter, to save the class comparison check. However, this will not work as expected when that is the only override.
=== 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
----
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
}
}
class MyClass2 {
public boolean equals(MyClass2 o) { // Ignored; `boolean equals(Object)` also present
//..
}
public boolean equals(Object o) {
//...
}
}
----
=== 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
----
class MyClass {
private int foo = 1;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MyClass other = (MyClass)o;
return this.foo == other.foo;
}
/* ... */
}
class MyClass2 {
public boolean equals(MyClass2 o) {
//..
}
public boolean equals(Object o) {
//...
}
}
----
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[]