Saturday, July 6, 2013

Test your equals methods

I found out one simple, clever and so obvious thing I couldn't imaging. It is testing equals methods. You can say: what's the point? Why should I do it? It contains simple code, which in most cases is generated by you IDE. And you are right.
But there is another point we should deal with. In Java there are few rules that must be obeyed by every developer: objects must be reflexive, symmetric and transitive.
Lets take a look at every of them.

 

Reflexivity

Any instance must be equal to itself:
assertTrue(x.equals(x));

Symmetry

If we have two instances and the first one instance is equal to the second one, then this equality must be also valid in opposite direction:
assertTrue(x.equals(y));
assertTrue(y.equals(x)); 

Transitivity

In case if there three instances, where:
assertTrue(x.equals(y));
assertTrue(y.equals(z));
the last pair must also be equal:
assertTrue(x.equals(z));

And more

And also don't forget about:
  • hashCode and equals relation, which says that if two instances of a class are equals, then they have to have same hashCode value:
    assertTrue(x.equals(y));
    assertEquals(x.hashCode(), y.hashCode());
    But in case if two hashcodes are equal, instances don't need to be equal as well.
  • equals method must always return the same value for every call on two instances unless one of them has been changed.
This note is related to presentation by Matt Stine: Effective Java Reloaded.

No comments:

Post a Comment