Saturday, 16 July 2016

Findbug : Unusual equals method (EQ_UNUSUAL)

I came across this find bug issue in my code recently. It appeared on the all the equals methods that had overidden the objects equals. The equals method that was there look fine to me.

Definition of the issue.

http://findbugs.sourceforge.net/bugDescriptions.html#EQ_UNUSUAL
This class doesn't do any of the patterns we recognize for checking that the type of the argument is compatible with the type of the this object. There might not be anything wrong with this code, but it is worth reviewing.


What patterns does find bug look for? 

Here is the source code for the equals pattern detection.


In the method visit() there is a nested if else statement. This method is checking what equals pattern was found by method sawOpcode(). At the end of the nested if statement is this code:


 else {  
         if (AnalysisContext.currentAnalysisContext().isApplicationClass(getThisClass())) {  
           bugReporter  
           .reportBug(new BugInstance(this, "EQ_UNUSUAL", Priorities.NORMAL_PRIORITY).addClassAndMethod(this));  
 }  

This code will flag the "Unusual equals method" issue since it has checked your code against every pattern it knows.

Does your code have an issue?

Probably not since it has checked all other possible issues you could of had with your code. Like the 2 issues below. It will make you think about your equals method thought. Wondering for ages why FindBug does not like your equals method.

Some patterns it is looking for

Patterns it does not like
EQ_ALWAYS_FALSE and EQ_ALWAYS_TRUE pattern is when it is returning a boolean and the previous opcode was ICONST_0 or ICONST_1. That means the equals method always returns the same boolean regardless of input so this is flagged as EQ_ALWAYS_FALSE or EQ_ALWAYS_TRUE in findbug.

EQ_GETCLASS_AND_CLASS_CONSTANT is when you are comparing the class to another class but you are using the class name instead of "this" variable. Subclasses will be broken if they are inherit this equals.


Patterns findbug likes in an equals method
A method call to compare
An Instanceof check
A method call to getClass

No comments:

Post a Comment