FindBugs controversal description

Posted by Tom Brito on Stack Overflow See other posts from Stack Overflow or by Tom Brito
Published on 2010-03-22T02:09:54Z Indexed on 2010/03/22 2:11 UTC
Read the original article Hit count: 507

Filed under:
|
|

Am I understanding it wrong, or is the description wrong?

Equals checks for noncompatible operand (EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS)

This equals method is checking to see if the argument is some incompatible type (i.e., a class that is neither a supertype nor subtype of the class that defines the equals method). For example, the Foo class might have an equals method that looks like:

public boolean equals(Object o) {
  if (o instanceof Foo)
    return name.equals(((Foo)o).name);
  else if (o instanceof String)
    return name.equals(o);
  else return false;

This is considered bad practice, as it makes it very hard to implement an equals method that is symmetric and transitive. Without those properties, very unexpected behavoirs are possible.

From: http://findbugs.sourceforge.net/bugDescriptions.html#EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS

The description says that the Foo class might have an aquals method like that, and after it says that "This is considered bad practice". I'm not getting the "right way"..

How should the following method be to be right?

@Override
public boolean equals(Object obj) {
if (obj instanceof DefaultTableModel)
    return model.equals((DefaultTableModel)obj);
else
    return false;
}

© Stack Overflow or respective owner

Related posts about java

Related posts about findbugs