Object javadocs and Josh Bloch tell us a great deal about how hashCode/equals should be implemented, and good IDEs will handle fields of various types correctly. Some discussion about all that is here.
This question is about the next step: How do you make sure that they remain good?
In particular, I feel that for most Classes, equals/hashCode should be implemented as Bloch suggests (and Eclipse and other IDE's implement), and take in to account all non-derived, business-logic, fields on that class. While adding new fields to a class as part of continuing work, people often forget to add them to the equals/hashCode implementation. This can lead to hard-to-find bugs, when two objects appear equal, but in fact differ by the value of a recently introduced field.
How can a team (even of one!) help ensure that the equals/hashCode on a class continue to take in to account all relevant fields, as the member fields change?
I know that Apache's EqualsBuilder and HashCodeBuilder can use reflection, which obviously would take in to account the correct fields, but I want to avoid the performance costs of using them. Are there other approaches to flag up fields that are not included in equals/hashCode, and should be? Static code analysis, IDE features, unit test techniques?
The only contractual obligation for hashCode is for it to be consistent. The fields used in creating the hashCode value must be the same or a subset of the fields used in the equals method. This means returning 0 for all values is valid, although not efficient. One can check if hashCode is consistent via a unit test.
If two Objects are equal, according to the equals(Object) method, then hashCode() method must produce the same Integer on each of the two Objects.
if a class overrides equals, it must override hashCode. when they are both overridden, equals and hashCode must use the same set of fields. if two objects are equal, then their hashCode values must be equal as well. if the object is immutable, then hashCode is a candidate for caching and lazy initialization.
Java equals() and hashCode() methods are present in Object class. So every java class gets the default implementation of equals() and hashCode().
Never tried it, but how about http://code.google.com/p/equalsverifier/?
A potential answer seems to be offered in this question.
I haven't looked into Project Lombok much, but I immediately thought, hmm annotations would work with a code generator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With