Saturday, June 5, 2010

New Way to Write Equals.

This is typical way to write the important equals method in java :

@Override
public boolean equals(final Object object) {
       if (this == object) {
              return true;
       }
       if (!(object instanceof MyClass)) {
              return false;
       }

       // now comes the real comparison of fields, foo, bar, etc.
       }

My idea is to refactor the later part of the comparison to another method :

public boolean equals(final MyClass myClass) {
       // Do the real comparison of fields, foo, bar, here.
}

So the original equals method becomes :

@Override
public boolean equals(final Object object) {
       if (this == object) {
              return true;
       }
       if (!(object instanceof MyClass)) {
              return false;
       }
       return equals((MyClass) object);
}

Benefit of having two equals is obvious, it keeps it simple and clear. In most cases equals will be only called with the object of same class only. In that case, it comes directly to the specific method, so it might be tiny bit faster as the instanceof is not being checked. Also first six lines of the method could be refactored into another method so the equals method
becomes even more compact.