Reputation: 49077
Can I use the same aggregate class as a member in other classes? And if yes would the class that contains the aggregate enforce access etc on that?
Let say you have a User class. Then a class named LogBook and at last a class named Log/Post (something down that alley). The LogBook would be an aggregate root for the Log/Post class and the User would be the overall aggregate in my example. Now, would the User class contain methods for adding log-posts etc? You would make one method in the User class that invokes LogBook class which has a method that does all the logic for actually adding a log.
Or, is a aggregate ALWAYS on top of the hierachy? No nesting.
Upvotes: 0
Views: 2606
Reputation: 2713
Here is a nice definition of an Aggregate:
Definition: A cluster of associated objects that are treated as a unit for the purpose of data changes. External references are restricted to one member of the Aggregate, designated as the root. A set of consistency rules applies within the Aggregate's boundaries. Problem: It is difficult to guarantee the consistency of changes to objects in a model with complex associations. Invariants need to be maintained that apply to closely related groups of objects, not just discrete objects. Yet cautious locking schemes cause multiple users to interfere pointlessly with each other and make a system unusable. [DDD, p. 126] Solution: Cluster the Entities and Value Objects into Aggregates and define boundaries around each. Choose one Entity to be the root of each Aggregate, and control all access to the objects inside the boundary through the root. Allow external objects to hold references to root only. Transient references to the internal members can be passed out for use within a single operation only. Because the root controls access, it cannot be blindsided by changes to the internals. This arrangemens makes it practical to enforce all invariants for objects in the Aggregate and for the Aggregate as a whole in any state change. [DDD, p. 129]
I don't think you want the User class reaching into the LogBook's aggregated objects without going through the LogBook class. However, accessing the LogBook from User seems OK.
Upvotes: 2
Reputation: 2118
I think the internals of an aggregate are allowed to hold references to the root of other aggregates. But each aggregate is responsible for enforcing its own boundaries. There is nothing stopping other objects from accessing the "referenced" aggregate completely outside of the first one - i.e. I don't think that nesting or ownership is implied just because one aggregate references another.
In your example, it seems like LogBook would fit better as an aggregate, controlling access to posts. Trying to shoehorn this into a larger User aggregate seems to be an awkward factoring of responsibilities.
Upvotes: 0