3
votes

I'm novice in DDD and CQRS patters and I want to have your opinion how a domain entity can be validated. I'm going to use the common example Order->OrderLine, where Order is the AR.

The validation of business rules in an Aggregate is through the AR for consistency matters. How can I validate a business rule that need data outside the Aggregate of Order?

I'm using also CQRS approach and I think that using the ReadModel to get the data that I need to make the validation of my business rules is not a bad option...What do you think?

2
Validation usually implies input, so it would happen on the command side (write side). What validation would you be doing on the read model?Davin Tryon

2 Answers

3
votes

With my experience of CQRS I associate the ReadModel as being eventually consistent, and therefore I wouldn't be 100% confident in the ReadModel representing the current state of the system. This becomes more the case when you want to distribute and replicate your ReadModels.

I would only want to use the ReadModel to limit the number of invalid commands being sent to your application.

It sounds to me that you want to start thinking about Domain Services, which can be used to encapsulate domain logic that falls outside the boundary of a single aggregate/entity/value object.

As David points out here Implement Domain Services as Extension Methods for the repository, Jimmy Bogard has a definition http://lostechies.com/jimmybogard/2008/08/21/services-in-domain-driven-design/

-1
votes

Yes, use the read model for command validation. I call this "command context" - the current state of the world, based on which command may be valid or invalid. In CQRS, this current state of the world is represented in your read model. User is making decisions based on it, what commands should be issued.

You may also consider various ways to guide user decisions, so that he doesn't issue invalid commands (warn in advance if username in not unique, etc).