Validation Design Pattern

10,200

Solution 1

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).

Solution 2

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.

Share:
10,200
TheITGuy
Author by

TheITGuy

Updated on June 13, 2022

Comments

  • TheITGuy
    TheITGuy about 2 years

    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 which is better? Anyone got any better idea?

    Thanks

  • anar khalilov
    anar khalilov over 6 years
    could you please add/rewrite sample usage code to include more explanatory class/method names?