Avoid Equals methods not testing their parameters

Why you should care

Because the equals method takes a generic Object as a parameter, any type of object may be passed to it. The method should not assume it will only be used to test objects of its class type. It must instead check the parameter’s type.

CAST Highlight considers that the type of the parameter will be checked if the Equals method contains a “if” statement whose condition is checking <p>.getClass(), where <p> is the name of the parameter.

How we detect

CAST Highlight counts one occurrence each time an Equals method doesn’t test its parameter type using if + <p>.getClass().

Bad Code

class myClass {
equals(Object c) {
// no if (c.getGlass() ....) check ...
}
}

Good Code

class myClass {
equals(Object c) {
if (c.getClass() eq "myClass") {
...
}
...
}
}

References

5362

About CAST and Highlight’s Code Insights

Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.