Currently, I was working on improving code quality. Some of the violations were due to the code generated by eclipse for hashCode() and equals() methods in the domain model classes. I was thinking on writing a builder classes for these methods, later on I just came across the Apache Commons Lang builder classes. It was even better than I imagined:)
Actually, the Apache Commons org.apache.commons.lang.builder package contains builder classes to help implement methods like equals() , hashCode() , compareTo(), and toString().. They are implemented to follow rules from in Effective Java , by Joshua Bloch
Considering clarity, readability and maintainability of the code, they are very concise and consistent solution.
The EqualsBuilder
Here is the sample usage of EqualsBuilder from API docs.
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof MyClass)) {
return false;
}
MyClass other= (MyClass) obj;
return new EqualsBuilder()
.appendSuper(super.equals(obj))
.append(field1, other.field1)
.append(field2, other.field2)
.append(field3, other.field3)
.isEquals();
}
It is good to be carefull with isEquals() method, it is a common mistake to use equals() of the EqualsBuilder instead of isEquals().
The HashCodeBuilder
Here is the sample usage of HashCodeBuilder:
public int hashCode() {
return new HashCodeBuilder().
append(field1).
append(field2).
append(field3).
toHashCode();
}
It is good to be careful again with toHashCode() method, it is a common mistake to use hashCode() of the HashCodeBuilder instead of toHashCode().
Alternatively, you can use the reflection-based static methods:
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(this, o);
}
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
However, I think reflection implementations are not good for a real project: They are potentially much slower and it is very important for domain model, the fields icluded in these methods should be carefully and intentionally selected considering the implication on the model.