Mich44
Mich44

Reputation: 95

DDD - always valid domain

Let's say we have a class Product with one field called name. This field has to be unique in the domain. Each product is persisted to database. In order to fulfill always valid approach, we shouldn't let create Product with a name which already exists in the database.

So far I found two approaches:

  1. Pass ProductValidator class as the parameter to changeName() which seems weird for me.
  2. Allow to change name of the product and then check the constraints, which violates Always valid approach rule.

Are there any better solutions/patterns to meet the requirements of the always valid approach and meanwhile DDD?

Upvotes: 1

Views: 349

Answers (1)

VoiceOfUnreason
VoiceOfUnreason

Reputation: 57194

The name for the general problem you are trying to solve is set validation.

The most common answer is: don't try to have that problem. Consider: what is the business impact of a duplicated product name? Is it something that must never happen (eg: criminal liability), or is it merely something that will negatively impact our productivity until we fix it?

If it is just something that should get fixed, then detection and escalation is probably a more efficient way to invest your design capital. That's especially true if the cost of fixing the problem is small.

On the other hand, if duplication has Dire Consequences, then you need to look to designs where the set-of-names is a single thing of its own, and it alone has control over which names are assigned to which products.

In domain driven design terms, the set-of-names must be its own aggregate, responsible for ensuring that this critical invariant is never violated.

This doesn't necessarily means we need all of the domain model ceremony. Relational databases are really good at set validation, providing you can ensure that the entire set is stored in a single database.

Upvotes: 1

Related Questions