Jonathan Goldberg
Jonathan Goldberg

Reputation: 1

In Domain Driven Design - single public entity model, or model per bounded context?

In Domain-Driven Design, we try to separate concerns between the functional areas (bounded contexts), and minimize dependencies between the contexts. The same entity can have different internal representation in different contexts. But in the communication between contexts (e.g. exposed APIs and/or events), do we tailor the representation of entities to each data consumer, or rather do we use a common representation?

For example, take the well-known separation (as diagrammed by Martin Fowler) between the Sales and Support contexts. Both contexts need to be aware of Customer and Product. But in Support context, a Customer has a list of Tickets; while in Sales context, a Customer is assigned to a Territory. Quite possibly, the internal representations will be completely different in the two contexts. But for exposed APIs and events, do we have a single Customer model that includes both these features, or do we have multiple models per context.

Upvotes: 0

Views: 245

Answers (1)

Subhash
Subhash

Reputation: 3270

The point of having separate bounded contexts is to have the freedom to express an entity in a way that is suitable to that particular context without having to worry about the rest of the system. That is how you would primarily manage functional clarity and data sanctity within the bounded context. So it definitely makes sense to have the Customer represented differently across contexts.

You can think of separate bounded contexts as different Microservices. They are deployed and scaled separately and don't share data. Their APIs are separate, catering to their own context's functionality. They own the models and are responsible for maintaining data sanctity within their boundaries without worrying about the rest of the application.

Note that you often have to preserve the same identity across contexts when you have different models for a related concept. You accomplish this by publishing domain events from the first context that initialized the entity, for other contexts to populate themselves appropriately.

In Fowler's example, the sales context might be the first context where a customer is initialized. So the sales context would generate the identity. The support context then adds a record to itself by listening to the CustomerCreated domain event, for example, anticipating future support calls from the customer.

When you need to collate data from different bounded contexts, you typically write a separate query or reporting service that operates with straightforward queries outside the domain logic. Views/Queries that fetch data and organize it for presentation normally stay outside domain logic.

Upvotes: 3

Related Questions