0

I have simplified the question here to narrow the focus:

What are some recommended approaches to performing validations in the Domain Layer for entity construction when data from a repository is needed?

For example, consider the following validation rule required to pass before an entity is created:

Rule 1: An employee requesting for a cell phone must have worked for ABC Company for 6 months or more

The information available to the Entity in the Domain Layer which originated from a UI and later passed in from an Order Service in the Application Layer does not have enough information to enforce the above sample rule. A query is needed from a repository to return the hire date of the employee to calculate if they have worked for 6 months or more.

The Question

The question is what layer or service should contact a repository at this point to get the employee hire date needed to validate Rule 1? The Domain Entity is not considered valid unless Rule 1 is passes and the entity's other data values pass as well.

Thanks in advance.

Robertcode
  • 911
  • 1
  • 13
  • 26

1 Answers1

0

Should the call to the repository to get the OrderValidationData be in the Application Service or should it be in the domain layer.

A domain validation is domain, thus, it should be part of a service within the domain.

You just need to imagine more than an application service interacting with some domain where the data being processed by the domain isn't enforced with validation in the domain itself. This is very dangerous because if some of the application services doesn't perform the so-called validation then the domain may get broken!

If it is in the Domain Layer then I guess I'll have to inject an instance of the repository needed to make the calls for the OrderValidationData? Also, since I've read people don't add repository operations into an Entity then I would have to create a Domain Service to do the repository actions.

Rich domain model vs anemic domain model (see Rich vs Anemic Domain Model)

And what about validating your domain in your repository? If you've already implemented a ProductRepository, I believe that your best bet is validating domain objects when they're going to be added or updated. That is, all upper layers must mandatorily follow the rules of repository and this means that you've reduced to zero the chances of breaking your domain model.

BTW, I would implement these validations as specifications (see Specification pattern) so you can validate your domain in an early stage of some operation before the domain object gets persisted by the repository. It might happen that you need to validate the same domain object within the same operation and specifications are a good friend to reuse validation rules in a n-layered architecture.

Community
  • 1
  • 1
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206