With reference to Eric Evans' Domain Driven Design: Tackling Complexity In The Heart of Software, a key attribute of value object is that they are often transient (i.e. short-lived), created for a specific operation and then discarded. If you are using programming languages that don't have any built-in automatic garbage collection mechanism (like C, C++), you will have to manually free up their memories at the end of their lifecycle. Otherwise, you shouldn't need any heavy duty implementation to manage them. (Eric Evan talked about garbage collection when comparing Entities
and Value Objects
too.)
The immutable aspect of value objects simply means that once created, none of their attributes can be modified except by full replacement of the entire object. So if two Person
entities shared the same Address
value object, and one of them changes her address, a new separate Address
value object will be created to represent the new address.
Of course, this is not a die-hard rule. Legitimate cases for mutable value objects include:
- If the value objects change frequently,
- Their creation and/or deletion processes are computationally expensive,
- Their replacement (instead of modification) disrupt the stability of the system,
- etc.
Another aspect of value objects is that they have no conceptual identity. But that doesn't mean they can't have low-level identifiers such as a column marked as their primary key in a relational database. Eric Evans also talked about association between entities and value objects. So if you decided to shared an Address
value object between two Person
entities, you can determine if the address already exists by querying the database, or whatever shared in-memory data structure accessible to the entities.