Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the recommended way to add child entities to aggregate roots?

Which is a better approach, create child entities first, then pass to the aggregate root to add them, or have the aggregate root create them? For example:

Order.AddOrderLine(new OrderLine(product, quantity, ...));

Or

Order.AddOrderLine(product, quanity, ...);

Which is a better approach? I'm sure this is purely subjective, but I want to see which has more pros vs cons.

like image 865
Jason Avatar asked Jan 24 '11 19:01

Jason


People also ask

Can aggregate roots share entities?

As you rightly pointed out, Entity instances shouldn't be shared between aggregates, as one aggregate wouldn't be aware of changes to the entity made through another aggregate and couldn't enforce its invariants.

What is an aggregated root?

Aggregate Root is the mothership entity inside the aggregate (in our case Computer ), it is a common practice to have your repository only work with the entities that are Aggregate Roots, and this entity is responsible for initializing the other entities. Consider Aggregate Root as an Entry-Point to an Aggregate.

How do you determine the aggregate root?

When choosing an aggregate root you choose between Transactional Consistency and Eventual Consistency. When your business rules allow you would rather favour Eventual Consistency.

Can an aggregate root contain another aggregate root?

So in its own bounded context then yah you could say it's and aggregate root. In DDD you can reference an aggregate root from another aggregate. What you cannot do is reference anything inside the other aggregate root.


1 Answers

Ok, so basically my opinion is that you should create an object before, because:

  • creating of the object is itself a separate concern, which can be a fairly complex by the way. And if, for instance, constructor of the OrderLine will be changed later you will need to change an Order type too. This is bad, cos you will need to change the Order only because of some changes in the OrderLine. So interface of the Order Root shouldn't depend on the OrderLine.

  • the second approach may be hard to test if you method will contain some additional logic exept of only calling this.OrderLines.Add(orderLine);

Edit After discussing this with a friend of mine, I came up with the following opinion:

  • Order Root should control lifetime of his child, because this will be more clear for other person who uses this API and will minimize the possibility of an inappropriate usage. And also will better reveal intent.

  • Using this approach also allows us not to worry about validating incoming OrderLine, because if we are responsible of the OrderLine creation then we can create it properly.

like image 156
Restuta Avatar answered Sep 21 '22 18:09

Restuta