Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should override Object.Equals for Entities (in DDD)?

From Framework Design Guidelines:

DO NOT implement value equality on mutable reference types. [p-270]

From Eric Evans's DDD:

Each ENTITY must have an operational way of establishing its identity with another object. [p-94]

Should I treat overriding Object.Equals method as identity operation or just compare the Identity attribute (e.g. customer1.Id == customer2.Id)?

like image 585
Soe Moe Avatar asked Jul 14 '09 15:07

Soe Moe


2 Answers

There are three cases you might want to be able to distinguish.

  1. You have two references to the same entity. In this case the normal equality operators will do their jobs correctly. No need to override anything.

  2. You have two instances in memory of the same entity. When you design your repositories right this situation is avoidable but sometimes this is a situation you'll have to work with. Your customer1.Id == customer2.Id example will work fine in this case.

  3. You have two different entities but you want to know if they have similar property value's. This might be a code-smell. You might be treating a value type as an entity. If this is really something you want to do then you should implement it separately from the normal .net == and .Equals mechanisms. (for example .IsSameAs(Customer subject)) to avoid confusion.

like image 117
Mendelt Avatar answered Oct 19 '22 15:10

Mendelt


In case you consider overriding Object.Equals you have to keep in mind that you have also to override GetHashCode().

like image 38
Juri Avatar answered Oct 19 '22 15:10

Juri