R – Entity/value object selection

domain-driven-design

In domain driven design, it is common knowledge that an object with an identity is an entity. For example, any person will have several forms of identity (name, etc).

But value objects are those objects with no identity. One common value object is address, however address has no identity. But at the database layer, we can have a composite key. Does this concept work in DDD? It would make address identifiable by the combination of roadname, postcode and door number (omitting information such as town and city). Money would be another value object.

The distinction seems to be in objects with no single identifiable field and value objects tend to not actually belong the entity. For example, "I" (replace with my name) may wear shoes etc but "I" am not shoes, shirt, etc (http://www.lostechies.com/blogs/joe_ocampo/archive/2007/04/23/a-discussion-on-domain-driven-design-value-objects.aspx).

Is this the right way to think about things? Also, with this mentality/approach, I can apply this to value/reference type selection in C#. I may as well go with the DDD approach though?

Thanks

Best Answer

I think you have the concepts of the distinction between entities and value types correct as they are understood within domain driven design (though I am far from an expert in this matter - perhaps better to say you match my understanding of these concepts). However I would advise against using this as a deciding metric when choosing whether to model those objects as reference or value in C#.

The key difference between a value and reference type is that the value types are copied when they are passed to a method. This means that they are more likely to sit on the stack rather than the heap and can be more costly to pass around; as such the size becomes a factor for consideration. The recommendation is that a struct should be below 16 bytes in size (at the bottom of remarks here) and a comprehensive address structure (House Number, House Name, Street Region, City, Country etc...) will easily break this.

That being said though, the semantics of entity:value :: class:struct are very similar and I can see a lot of benefits from modelling the data that way (two people who live at the same address don't share that address since changing one person's address shouldn't change the other's. So having the address as a struct would enforce this kind of separation. Whereas all instances of a person in the application should point to the same person). But there are performance and memory considerations. Perhaps immutable classes would be a good fit for these value types?

To sum up: The distinction between entity and value in DDD is based around what the object is. In code is should be based on what you intend to do with it.

Related Topic