2

I'm trying to understand the concept of value object. One aspect of value object is immutable. I would like to know that do we have to implement a thing that manages value object? For instance, Person is entity and Address is value object. Two person have same address.

  1. + Can we assign the same instance address for each person?
  2. + How do we know the address already existed so we don't need to create new one?
  3. + How we manage value object?

I don't whether i understand immutable aspect correct or not. Could you please advice me on this matter?

ck_forest
  • 21
  • 1

1 Answers1

2

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:

  1. If the value objects change frequently,
  2. Their creation and/or deletion processes are computationally expensive,
  3. Their replacement (instead of modification) disrupt the stability of the system,
  4. 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.

ivan.sim
  • 8,972
  • 8
  • 47
  • 63