Unit testing equals and hashcode - a complexity story

I'm thinking of using EqualsBuilder and HashcodeBuilder from apache commons-lang to circumvent this, but I'm not 100% happy :S.

Why not use these?

Using them reduces the size and complexity of your own methods and it's much easier to verify visually that equals and hashCode are implemented consistently.

It's of course also a good idea and pretty easy to test that the equals/hashCode contract is satisfied, so by all means, write tests.


I think that your real problem is placing too much faith in artificial measure such as code coverage cyclomatic complexity.

The plain facts are that:

  • the generated code is correct ... modulo that you have chosen the correct model of equality, and
  • the generated code is not complicated ... or at least, no more complicated than it needs to be.

Learn to trust your own judgment, and stop relying on tools to make your design decisions for you.


And the corollary of what I just said is that if you think you can (and should) simplify the generated code while still ensuring that it is correct for your current and projected use cases, go ahead and simplify it.


By the way, a generated equals / hashcode pair are probably more likely to be more correct than a hand written one ... written by an "average bear" programmer. For instance, note the careful way that the generated code handles null fields and the comparison of the types. A lot of developers wouldn't get those right.