This question is specifically related to overriding the equals() method for objects with a large number of fields. First off, let me say that this large object cannot be broken down into multiple components without violating OO principles, so telling me ‘no class should have more than x fields’ won’t help.
Moving on, the problem came to fruition when I forgot to check one of the fields for equality. Therefore, my equals method was incorrect. Then I thought to use reflection:
--code removed because it was too distracting--
The purpose of this post isn’t necessarily to refactor the code (this isn’t even the code I am using), but instead to get input on whether or not this is a good idea.
Pros:
- If a new field is added, it is automatically included
- The method is much more terse than 30 if statements
Cons:
- If a new field is added, it is automatically included, sometimes this is undesirable
- Performance: This has to be slower, I don’t feel the need to break out a profiler
- Whitelisting certain fields to ignore in the comparison is a little ugly
Any thoughts?
If you did want to whitelist for performance reasons, consider using an annotation to indicate which fields to compare. Also, this implementation won’t work if your fields don’t have good implementations for
equals().P.S. If you go this route for
equals(), don’t forget to do something similar forhashCode().P.P.S. I trust you already considered HashCodeBuilder and EqualsBuilder.