Search code examples
domain-driven-designddd-repositories

DDD, Aggregates and Repos


I have the following entities (example):

  • Book
  • Author

The Book entity is also an aggregate since it has related one or many Authors. Now I have a problem in how to fetch this aggregate from the repo. I have the following cases - and I also do need to take care of performance:

  1. List all the Books. No need to fetch Authors.
  2. List all the Bookss with Authors names. Obviously, we need to fetch the aggregate of Books and related Authors.
  3. List all the Books with authors count. Similar to (2), except I do not want to fetch the Authors from the repo, just the count.

So how my repository should look like? Specific questions:

  • Should we have method like findBooks and findBooksWithAuthors and findBooksWithAuthorsCount? But this would lead to crazy amount of methods, since our entities have many relationships between each other.
  • Should we just have findBooks and then loadAuthors in AuthorsRepo, i.e. not doing the join, until we hit some performance issue, and then to refactor.
  • Should I create some aggregate-value-objects, like: BookAndAuthors that describes relationships?

Please note that this example is trivial - and you have to know that our models are more rich and have more relationships.


Solution

  • Do you need to fetch this kind of information to display on the UI ?,

    I would encourage you to separate your read and write concerns, and keep your repository interface simple (similar to that of a collections interface).

    Have a look at CQRS, it works very well with DDD and will help simplify your design to a great deal.

    Once you get into CQRS, just keep in mind that CQRS does not necessarily involve Event Sourcing.

    In your case I would recommend the simplest approach show in this article, basically have a read service (can call it Finder), which fires SQL and gets you a DTO/Map of whatever you need for the UI.