Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CQRS/DDD: Checking referential integrity

Should a command handler also check for referential integrity? This FAQ suggest that you shouldn't check this in the aggregates (http://cqrs.nu/Faq). Isn't checking that something exists part of the validation?

For example you can have an application where you can add comments to an article.

The command would have these fields:

  • Id
  • ArticleId
  • UserId
  • Text

For this example the comment and article are a different aggregateroot.

Should you check for this example if the article already exists and the user exists? It feels a bit strange that you can add a comment to an article that doesn't exists.

like image 403
Valderann Avatar asked Jan 30 '23 20:01

Valderann


1 Answers

I presume that you have a reason to divide Article and Comment into separate aggregate roots. When I face with a question like yours, usually it is an indication of the opportunity to rethink the domain model.

There is nothing wrong with referential integrity check but think about the eventual nature of the changes to the aggregates that don't belong to the same root. What does the result of the validation indicate?

If the article does not exist, is it because it was not added and you have an integrity issue in the command? Or maybe it was added but has not yet been propagated to the query side of the application? Or maybe it has been already removed before the user has posted the comment?

What if the validation confirms that the article exists? Maybe moderator has removed it, but the result was not yet propagated?

Remember, you could only rely on the order of events when they happen under the same aggregate root.

To summarize: you could verify referential integrity in a command handler as long as you realize that there might be false positives and false negatives. If you expect incoming commands to have unreliable data often, maybe this verification would limit the rate of errors. However, try to rethink the structure of your aggregates if the consistency is critical.

like image 123
oiavorskyi Avatar answered Feb 09 '23 00:02

oiavorskyi