DDD Using Specification pattern for Validation

前端 未结 2 1328
栀梦
栀梦 2020-12-04 16:16

I am thinking of using Specification pattern for validation purposes. The hard thing is how to tell the user why some Specification was not satisfied. What if the Spec

相关标签:
2条回答
  • 2020-12-04 16:23

    I had the same problem. I create Validation decorator for Specification (code is JAVA).

      interface Validator<T>{
        Respond validate(T t)
      }
    
    
      class abstract ValidationSpecificationDecorator<T> implements Validator<T> {
      Specification<T> spec;
    
      ValidationSpecificationDecorator(Specification<T> spec){
        this.spec =  spec;
      }
    
      public Respond  validate(T t) {
        Respond respond = new Respond();
        if(!spec.IsSatisfiedBy(t){
           respond.add(error(t));
        }
        return respond;
      )
    
      public abstract Error error(T t);
    
      }
    
    0 讨论(0)
  • 2020-12-04 16:29

    Although you may use your Specifications classes for validation, I would suggest you keep them as separate concepts within your domain. You may find that you need to re-use the same underlying specifications but need to return different "Failure Reasons" depending on purpose and context. See this article for more details.

    The author of the post referenced above has also kindly shared code to github and posted the code as NCommon. Review these areas in particular:

    Specifications: https://github.com/riteshrao/ncommon/tree/v1.2/NCommon/src/Specifications

    Validations: https://github.com/riteshrao/ncommon/tree/v1.2/NCommon/src/Rules (especially the classes for ValidationResult and ValidationError)

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