Search code examples
aggregatedomain-driven-designddd-repositories

Should a comment on a blog post be an aggregate root?


I’ve read that an aggregate should be encapsulated by its aggregate root. The aggregate should not exist if the aggregate root does not exist and we should access the aggregate though its root only.

Considering an example: i have a video website with a Few video and those videos can potentionally have lots of comments.

It seems to me that the video is the aggregate root and the comment is the aggregate, since a comment wouldn’t make sense without a video.

But how would i retrieve the comments without loading them all from the database? That would be a big performance hit. Lazy loading could be a solution but i’ve read that it is not recommended.

Comment could be its own aggregate root, so i can query it independently, but that would break the “existence without root” rule, right?


Solution

  • You are capturing yourself by thinking about aggregates from a persistence perspective. Within aggregate, it is not important if something is part of something or if something has something. Those are relational terms. What is important is the conceptual unity of objects that share the same root. A side effect of this unity is a transactional boundary - which is then used to save aggregate with the help of repository and storage mechanism. Aggregate doesn't care if it is going to be saved. Repository interface (as part of the domain) is there just because we are constrained by the architecture which includes the database. Pay attention to behavior, business rules, cohesion. Aggregation is much complex process then it is presented in DDD books.

    Take a look at game of life. These small squares are all aggregated around some common root. They don't care if they are going to be saved. They are just fulfilling their mission. They are not part of an aggregate, they are part of something more dynamic and complex. Saving snapshots of Game of life in DB doesn't tell you much about their nature.

    enter image description here

    Also, don't think about a query as something fixed. Aggregate can be loaded and fetched in many different ways (partially or as a whole). This is the job of application. Thinking about query first means that you think about aggregate as a collection of data.