How to share validation between Forms and Value Objects in Domain Driven Design?

后端 未结 1 1055
执笔经年
执笔经年 2020-12-11 05:27

#1. Validate EmailAddress on the Form

I have a backend form class with an emailAddress property that has validation logic so that I can

相关标签:
1条回答
  • 2020-12-11 06:12

    Encapsulate the validation logic into a reusable class. These classes are usually called specifications, validators or rules and are part of the domain.

    There are multiple ways of doing this, here is an approach that I use:

    1. Define an interface Specification that provides a bool IsSatisifed() method.
    2. Implement this interface for a specific value object, e.g. EmailWellformedSpec.
    3. Enforce the business rule within the domain by using the spec as precondition (i.e. violation is always a programming error).
    4. Use the spec for input input validation in the service layer (i.e. violation is a user error).

    If you want to combine multiple specs to a larger one, the Specification Pattern is a good approach. Note that you need to pass in the data through the constructor if you use that pattern, but this is not a problem because the specification classes are usually simple.

    0 讨论(0)
提交回复
热议问题