Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how should i add an object into a collection maintained by aggregate root

lets say i have a BlogPost aggregate root. it holds a List<Comment>.
how should the BlogPost AddComment signature look? is it OK to use:

public void AddComment(Comment comment)
{
    Comments.Add(comment);
}

or should i avoid creating references to root's children outside of it, and do something like this:

public void AddComment(string text, string email)
{
    Comment comment = new Comment(text, email);
    Comments.Add(comment);
}
like image 734
Asaf David Avatar asked Feb 19 '09 19:02

Asaf David


People also ask

How do you choose 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.

What is an aggregate root?

An Aggregate is the clump of related entities to treat as a unit for data changes. The Aggregate Root is the main entity that holds references to the other ones. It's the only entity in the clump that is used for direct lookup.

Can a value object be an aggregate root?

Thus, the aggregate root must be an entity, not a value object, so that it can be persisted to and from a data store using its ID.

Can an aggregate root reference another aggregate root?

[Evans] states that one Aggregate may hold references to the Root of other Aggregates. However, we must keep in mind that this does not place the referenced Aggregate inside the consistency boundary of the one referencing it.


1 Answers

If you consider Comment to be an aggregate of BlogPost and to not make sense out of that scope then you should be using the second example.

The aggregate root should control how the aggregates are instantiated so their constructors should not be visible outside of the aggregate root.

Plus, Comment should be a child class of BlogPost if you want a true relation of AggregateRoot-Aggregate.

like image 152
mbillard Avatar answered Oct 28 '22 03:10

mbillard