javaarchitecturepackagedomain-driven-designentities

DDD: Aggregate and entities relationship


I read some of the publications and threads about DDD. There are many voices about connection between aggregate and entities. I understood that aggregate should be as simple as possible (one entity per aggregate). But what about situation when aggregate has collection of entities?

Let's say, we have one aggregate called "Month" which contains a collection of "Day" objects (that are domain entities, because they need an identity to be distinguishable - to let aggregate know which "Day" to modify).

So I have two questions:

  1. Is this a proper approach? Just a normal situation and I shouldn't be concerned?
  2. What about "visibility" outside? In my approach, an aggregate is "package-private" to not let anyone use it in different parts of the system. But what about entities? Should they be visible just like Value Objects for different parts of the system? Or just create another VO to represent entities outside (for example: when entities are stored in events)?

Thank you for all the answers


Solution

  • Modeling days and months as entities depends a lot on the context. It might not be the best example to explain aggregates and entities but let's give it a try.

    Let's assume that in our context a day can not exist on its own. It has to be within a month. If you want to refer to a day, you must specify the month first. That is how we use dates in real life, January 1st, May 8th ... Even though the days are entities they don't need a global uniques identifier. They only need an identifier within the month [1 .. 31].

    Aggregates should be as small as possible however it is not a rule that you should only have one entity per aggregate. You just need to have an aggregate root (month) that has a unique identifier across all the systems. Within the aggregate, you can have entities(days) that have a unique identifier within the aggregate[1 .. 31]. If you want to refer to or access these entities you should always go through the aggregate root.