Reputation: 95
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.
How can I implement such validation inside the Product class so I wouldn't be instanciated when name is not unique?
The same question can be applied for the changeName method.
public class Product {
private String name;
(...)
public Product(String name) {
// check if name is unique
this.name = name;
}
public void changeName(String name) {
// check if name is unique
this.name = name;
}
}
So far I found two approaches:
Are there any better solutions/patterns to meet the requirements of the always valid approach and meanwhile DDD?
Upvotes: 1
Views: 349
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