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.
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.
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.
When choosing an aggregate root you choose between Transactional Consistency and Eventual Consistency. When your business rules allow you would rather favour Eventual Consistency.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With