drizzie
drizzie

Reputation: 3361

How do I draw the line when applying the Domain Driven Design rule "only access aggregates via the aggregate root"

We have a SaaS application.

There are rows in the database for Companies, Users, and Entities (generic for stuff users deal with)

So Company A controls Users A-F

Users A-C have rights to view Entity A Users D-F have rights to view Entity B

When I create my bounded context for Entity A and its aggregate entities, should Entity A only be accessed via Company A?

I am trying to figure out where to apply the rule "only access aggregates via the aggregate root".

Where do I draw the line?

What about when Company A and Company B can both access Entity A?

Upvotes: 1

Views: 73

Answers (2)

guillaume31
guillaume31

Reputation: 14070

"Only access aggregates via the aggregate root" isn't a useful rule for aggregate design. It's only a practical byproduct of the concept of aggregate to keep in mind when programming -- if you could access any entity directly without restrictions, Aggregates would basically be useless.

When modelling you should instead look for entities that tend to change together in the same business transaction and/or must stay consistent together, and draw aggregate boundaries around those.

Chances are that no data in Company needs to be consistent with its Entities at all times and that they don't change together, so by virtue of the "keep aggregates small" recommendation, you should probably make them 2 aggregates. But only you know the invariants in your domain and can tell.

Upvotes: 2

theDmi
theDmi

Reputation: 18034

The idea about aggregates is that they represent consistency boundaries. This means that it should be possible to load two different aggregates at the same time, modify both, and save them back to the DB. As soon as you make the same entity part of multiple aggregates, this is not guaranteed anymore. Reasoning about consistency and concurrency in your domain becomes a lot more difficult if you do this.

This is why an entity must belong to only one aggregate.

The solution is usually simple: Make the entity it's own aggregate. This means that you can only reference it by ID from the aggregate where it was referenced by association before. Note that this also solves your "only access aggregates via aggregate root" problem.

Upvotes: 2

Related Questions