3

I am working on a project implemented in DDD style, and I use Repository architecture pattern to persist domain changes. I have multiple roles in domain layer, and that's what raises my question - how should my Repository handle this? Three solutions come to my mind:

  1. Separate Repositories for separate objects - (probably) the easiest one, but code might quickly turn into a mess;

  2. Improvement over (1) - use Factory pattern to create specific type of Repository;

  3. Keep a single Repository, but make it behave differently for different types of input (e.g. utilize Strategy pattern).

Is there any better way to handle this problem?

Some project information that might be useful:

  • Project is made with mostly Python;
  • There are not that many entities in domain - approx. 10;
  • Service layer is decoupled from database layer through Unit of Work pattern
Doc Brown
  • 206,877
  • The general approach is to have one repository per aggregate. – Rik D Nov 28 '23 at 18:17
  • Hello @RikD, thank you very much for your answer, it seems like I had to spend a little more time reading. Can you please make your comment a post so that I could mark it as answer? – lubitelpospat Nov 28 '23 at 18:44
  • 1
    I took the freedom to change the question's title, because in its original form, I think there was a certain risk to provoke "dupe close votes" for Choosing the right Design Pattern. Question where askers are "shopping" for patterns are not well received by our community. – Doc Brown Nov 28 '23 at 19:45

1 Answers1

7

In DDD, the general approach is to have one repository per aggregate.

An aggregate is a collection of closely related concepts that together form a consistency boundary.

For example an Order aggregate with OrderLines as a collection of child entities. There would be an OrderRepository, but no OrderLinesRepository. The OrderLines collection can only be modified via the Order. That way, the Order can enforce business rules (in DDD terms called invariants) that depend on the OrderLines, e.g. there should be at least one OrderLine in an Order.

Rik D
  • 4,801