开发者

Validation Design Pattern

I am wrting a data validation utility for one of our department which has following requirement. - Dynamically adding new business entity - Dynamically adding new validations to an entity. - An UI to display list of business entity and their validaiton - User will have option to start the validation on all or selcted business entity validaiton. - UI will display a validation error message if any validation fails. - System should proceed to the next validation even if any of the validation fails thus all configured validaiton are validated.

After searching internet I found following 2 promissing design pattern which satisfy my business requirement one id Decorator pattern and another is Chain of Command (aka Chain of Responsibilty). Now my question is 开发者_JAVA百科which is better? Anyone got any better idea?

Thanks


I think what you want is the Specification Pattern. So you would do something like this:

public void StartDateNotInPastSpecification : ISpecification<ISomeBusinessObject>
{
  public bool IsSatisfiedBy(ISomeBusinessObject myBusinessObject)
  {
    return myBusinessObject.StartDate >= DateTime.Now;
  }
}

The nice thing about this pattern is that each rule is easily testable in isolation and you get to choose when to apply the validation rules (as opposed to some frameworks which impose this decision on you).


I'm using the Specification Pattern too. This is a basic implementation of it.

public class Specification<T, E> : ISpecification<T, E>
{
    private Predicate<T> predicate;

    public Specification(Predicate<T> predicate)
    {
        this.predicate = predicate;
    }

    public bool IsSatisfiedBy(T candidate)
    {
        return this.predicate.Invoke(candidate);
    }
}

With this implementation, I just pass a predicate in the constructor, like this:

var specification = new Specification<SomeDomainClass>(x => x.SomeDomainBoolMethod());

Instead of several classes (one per each condition in my domain), I have several bool methods in my business objects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜