Implement hashCode and equals on base entity class (possibly using reflection)?
I am won开发者_如何学编程dering whether it is a good practice to have hashCode
an equals
method in the base entity class so that other entity classes that inherit the base class do not have to write their own hashCode
and equals
method?
Right now all our entity classes are using apache's EqualsBuilder
and HashCodeBuilder
, we are comparing all the entity's properties.
It gets kind of tedious since we have to do this for all entities, so I was wondering whether it is okay (in the base entity) to use reflection and apache's PropertyUtil to loop over an entity's property and generate the proper equals
and hashCode
?
If you are referring to an entity as in the DDD concept of an entity (a domain object with an identity in contrast to a value object or service), then yes, you should override the base class equality compare for your entity, and make it determine equality based on the Key or Id property of the entity.
Equality checks should always be custom made according to the business needs. Going with an one size fits all is not necessary. In many of the code bases I have seen equality check is driven by a business requirement and have tests backing it.
Sounds fine provided the base class can genuinely decide which fields to include in determining equality and how to compare them.
In general, there's a danger of letting base classes do comparison if they can't predict what subclasses will be being compared and hence how to compare all relevant fields. With entity classes in a typical situation, you won't have this problem.
精彩评论