Architecture – “Implementing DDD” by Vernon: value object or not

Architecturedomain-driven-design

On page 382 of this book there is a passage talking about using value objects in aggregates, under the (entity) root. There is an example of Product that, besides other values, contains a Set<ProductBacklogItem> – collection of entities.

Now, Vernon tries to explain why ProductBacklogItem is an entity and not a value object:

There are good reasons why ProductBacklogItem is modeled as an Entity rather than a Value. As discussed in Value Objects (6), since the backing database is used via Hibernate, it must model collections of Values as database entities. Reordering any one of the elements could cause a significant number, even all, of the ProductBacklogItem instances to be deleted and replaced. That would tend to cause significant overhead in the infrastructure. As an Entity, it allows the ordering attribute to be changed across any and all collection elements as often as a product owner requires. However, if we were to switch from using Hibernate with MySQL to a key-value store, we could easily change ProductBacklogItem to be a Value type instead. When using a key- value or document store, Aggregate instances are typically serialized as one value representation for storage.

I don't understand why the Repository implementation determines if some model is going to be an Entity or Value Object? If we go to the key-value store, we still may have ordering he is talking about.

Do you think this make sense?

Best Answer

The reason is that SQL databases store the objects in a relational way - items are stored in different table than aggregate root and they reference back to aggregate root by IDs. So using of MySQL requires to model items as entities that are persisted in separate table where they obtain primary id (with auto increment).

In key-value stores eg. MongoDB one can store the whole collection of items as part of the aggregate root. The items would not become separate entities (in its on table) and thus can be modelled as value objects.

Eg. Blog has Comments stored as collection within:

{
  _id: 1,
  title: 'Some title',
  body: 'Blog body',
  comments: [{
     person: 'John Smith',
     comment: 'First comment of the blog',
     created_at: new Date()
  },
  {
     person: 'Peter Jackson',
     comment: 'Second comment of the blog',
     created_at: new Date()
  }],
}
Related Topic