Wednesday 28 October 2009

Entities

Entities are the stars of the domain model. They are the most valuable elements in terms of amount of business logic. They usually represent the most important real life concepts - those which have its own identity. And identity is something which is critical to the entities.

Entities which have different IDs are different entities. That is what the books would told you. But how does it look like in practice?

In DDDSample there is special interface for entities: IEntity. It defines one method
boolean sameIdentityAs(T other)
Implementation checks whether the other object is null (in this case returns false) and, if not, compares business identities of the objects.

There is also the equals method overridden on all entity classes. equals compares all the data contained in particular entity.

I think I understand some of the reasoning behind this solution. The sameIdentityAs method makes explicit that we are comparing business, not database, keys and that we care about identity. What I don't understand is the equals method. Why on Earth should I compare entities by their value? Ideally (in CQS?) they should expose no values at all.

I decided to get rid of the equals (in my, C#, case Equals) overriding. That was the easy decision. Now the hard one: what to do with the SameIdentityAs? As you could read in the previous episode, I decided to get rid of similar method on value types. I think I had strong reasons there, but here?

The reason I consider giving up on the sameIdentityAs at all are ORMs. They provide me with an Identity Map out of the box - a warranty that two object references with same DB key are in fact one object instance on the heap. With that promise I can simply use == and != to compare addresses and the result is the same as business key comparison.

I strongly believe that all of my applications would use ORMs to store data in the foreseeable future. Even if I am wrong, in case I had to change my data access strategy completly, I wouldn't expect that the change would be simply switching the DLLs. It certainly would be a painful task. I won't make it easier just by pretending that I am not dependant on an ORM. Yes, I am and this fact is reflected clearly by the structure of the model. If I would plan to use OODBMS, I would structure my model completely different.

So, to sum up, we will get rid of those sameIdentityAs methods as well and use plain C# equality operators for both entities and value objects. In case of entities we will depend on Identity Map implemented in the ORM. It will make our code more consistent in context of object comparison.

No comments:

Post a Comment