2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-06-08 14:23:48 +02:00
Non ``++final++`` classes shouldn't use a hardcoded class name in the ``++equals++`` method. Doing so breaks the method for subclasses. Instead, make the comparison dynamic.
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-06-08 14:23:48 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-06-08 14:23:48 +02:00
----
public class Fruit {
private Season ripe;
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (Fruit.class == obj.class) { // Noncompliant
return false;
}
// ...
----
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-06-08 14:23:48 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-06-08 14:23:48 +02:00
----
public class Fruit {
private Season ripe;
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (this.class == obj.class) { // will work for subclasses too
return false;
}
// ...
----
ifdef::env-github,rspecator-view[]
2021-06-08 15:52:13 +02:00
'''
2021-06-08 14:23:48 +02:00
== Comments And Links
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== on 15 Oct 2014, 21:53:16 Freddy Mallet wrote:
@Ann, I would merge this rule with RSPEC-2162 as they both have exactly the same goal.
2021-06-08 14:23:48 +02:00
endif::env-github,rspecator-view[]