jeudi 18 octobre 2018

Validation in Domain Driven Design

Our team is starting a new project following Domain Driven Design (DDD). At the high level, we have an API on the top of our domain which enables a client to perform operations on the domain. One of the question I'm not very clear about is where do we perform validation on a certain property/ attribute in DDD.

Consider this example. Let us say, I have a below data contract/ DTO exposed by my API:

 public class Person
 {
    public string Email { get; set;}
    public string Name { get; set; }
 }

Now, let us say we have business rule which prevents user to enter an invalid email address and restricts user to have name more than 50 characters.

To achieve this, I can see following three approaches:

In Approach 1 , we do data validation only at the API (either through Data Annotation or Fluent Validation). I do not repeat the validation in my domain. Theoretically, this may mean my domain could go in an invalid state. But, since entry point (API) is being validated it is not possible in a real scenario.

enter image description here

In Approach 2, we do data validation at both API and in my domain. This approach helps us to completely remove coupling between my domain and API. The API can independently return a Bad request to the client. And since the domain performs the validation again, there is no chance of domain going to an invalid state. In this approach however, we violate DRY principle.

enter image description here

In Approach 3, we do validation only at Domain and do not perform validation on DTO at API level. With this approach, while we are not repeating the validation, the domain cannot throw an exception when API call tries to put it in an invalid state. Rather, we would need to wrap that exception in some Result object. This would help the API to send an appropriate response to client (eg. Bad request instead of Internal Server error). What I do not like about this approach is that I would rather prefer to throw a hard exception than put a wrapper. enter image description here

Ask

  • Which approach makes the most sense and why?

  • Where is the line between a business validation and a business rule? (Assuming the business rule exists in domain).

  • Is there anything obvious which I'm missing here?

Note: This question may look similar to Validation in a Domain Driven Design n and where should put input validation in Domain Driven Design? but it does not really answer the specifics.

Aucun commentaire:

Enregistrer un commentaire