Specifications versus validators

Joe posed a great question on my recent entity validation post:

I question the term Validator in relation to DDD.  Since the operation of the Validator seems to be a simple predicate based on business rule shouldn’t the term Specification [Evans Pg227] be used instead?

On the surface, it would seem that validation does similar actions as specifications, namely that it performs a set of boolean operations to determine if an object matches or not.

For those unfamiliar with the Specification pattern, it provides a succinct yet powerful mechanism to match an object against a simple rule.  For example, let’s look at an expanded version of the original Order class on that post:

public class Order
{
    public int Id { get; set; }
    public string Customer { get; set; }
    public decimal Total { get; set; }
}

A Specification class is fairly simple, it only has one method that takes the entity as an argument:

public interface ISpecification<T>
{
    bool IsSatisfiedBy(T entity);
}

I can then create specific specifications based on user needs.  Let’s say the business wants to find orders greater than a certain total, but the total can change.  Here’s specification for that:

public class OrderTotalSpec : ISpecification<Order>
{
    private readonly decimal _minTotal;

    public OrderTotalSpec(decimal minTotal)
    {
        _minTotal = minTotal;
    }

    public bool IsSatisfiedBy(Order entity)
    {
        return entity.Total >= _minTotal;
    }
}

Specs by themselves aren’t that useful, but combined with the Composite pattern, their usefulness really shines:

public class AndSpec<T> : ISpecification<T>
{
    private readonly List<ISpecification<T>> _augends = new List<ISpecification<T>>();

    public AndSpec(ISpecification<T> augend1, ISpecification<T> augend2) 
    {
        _augends.Add(augend1);
        _augends.Add(augend2);
    }

    public AndSpec(IEnumerable<ISpecification<T>> augends)
    {
        _augends.AddRange(augends);
    }

    public void Add(T augend)
    {
        _augends.Add(augend);
    }

    public bool IsSatisfiedBy(T entity)
    {
        bool isSatisfied = true;
        foreach (var augend in _augends)
        {
            isSatisfied &= augend.IsSatisfiedBy(entity);
        }
        return isSatisfied;
    }
}

Adding an “OrSpec” and a “NotSpec” allows me to compose some arbitrarily complex specifications, which would otherwise clutter up my repository if I had to make a single search method per combination:

OrderRepository repo = new OrderRepository();
var joesOrders = repo.FindBy(
    new AndSpec(
        new OrderTotalSpec(100.0m),
        new NameStartsWithSpec("Joe")
    ));

Given the Specification pattern (fleshed out into excruciating detail), why can’t I compose validation into a set of specifications?  Let’s compare and contrast the two:

Specification

  • Matches a single aspect on a single entity
  • Performs positive matching (i.e., return true if it matches)
  • Executed against a repository or a collection
  • Can be composed into an arbitrarily complex search context, where a multitude of specifications compose one search context
  • “I’m looking for something”

Validator

  • Matches as many aspects as needed on a single entity
  • Performs negative matching (i.e., returns false if it matches)
  • Executed against a single entity
  • Is intentionally not composable, a single validator object represents a single validation context
  • “I’m validating this”

So although validation and specifications are doing similar boolean operations internally, they have very different contexts on which they are applied.  Keeping these separate ensures that your validation concerns don’t bleed over into your searching concerns.

Related Articles:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Jimmy Bogard

I'm a technical architect with Headspring in Austin, TX. I focus on DDD, distributed systems, and any other acronym-centric design/architecture/methodology. I created AutoMapper and am a co-author of the ASP.NET MVC in Action books.
This entry was posted in Domain-Driven Design, Patterns. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • cramsay

    Fantastic post.

  • http://www.lostechies.com/blogs/joe_ocampo/ Joe Ocampo

    hmmmm….Maybe my understanding of a Specification differs from yours. I will have to think about this and ReRead yet again for the umpteenth time DDD[Evans 2003] on the Specification.

    From a high level my understanding is that the Specifications impose Ubiquitous predicate constructs in relation to Entity validation.

    Suppose during a dialog with the product owner, they inform you that for an order to be valid, that is has to be ordered as of a specific date and not be over a certain amount.

    I would then pose the question could we refer to this rule set as the “BasicOrderSpecification” ? Usually they say sure or we change the nomenclature to be more expressive for them. Now we have a common “Ubiquitous” term for dealing with the business rules in determining if an order is valid.

    Anytime I bring up the term “BasicOrderSpecification” the team (product owner, developer and QA) knows that I am referring to, must meet a certain ceiling amount and enforce this date rule.

    Order order = new Order();
    if (BasicOrderSpecification.IsOrderValid(order)…

    Aside from my banter, Great post! That is exactly how I model my Specifications but not how I utilize them.

  • Joe

    @Joe – I a huge fan of the specification pattern when looking for something / filtering, but i think with validation feedback is implied. A set of specifications will tell me that my order is not valid, but validation will tell me that my order is not valid because the selected delivery date is on a weekend. Your validation routines could certainly take advantage of the rules that you have coded into Specifications (and i suppose shoud — why repeat yourself?).

    At least that’s my take on it…
    BTW = Jeff Perrin did a great post on Specifications a while back: http://devlicio.us/blogs/jeff_perrin/archive/2006/12/13/the-specification-pattern.aspx

  • http://grabbagoft.blogspot.com/ Jimmy Bogard

    I had to go back and read it again, as I like to go from the Nilsson book sometimes. Here’s the spec purposes from Evans:

    1. To validate an object to see if it fulfills some need or is ready for some purpose
    2. To select an object from a collection (as in the case of querying for overdue invoices)
    3. To specify the creation of a new object to fit some need

    I mostly use it for #2. I could see using specs for #1, but I would still want the feedback part of knowing “why”. Specs are great for “if”, but I think I’d rather separate validation specs into new “IValidationSpec” interface that also gave me failure reasons.

    That is an interesting approach though, I’ll have to keep it in mind. Just when you thought you knew the Evans book inside and out…

  • http://craigcav.wordpress.com/ CraigCav

    Firstly, great post – i’ve been browsing through your feed all day and it’s been really inspiring – keep it up!

    I’ve often pondered the use of specifications when validating objects to keep my code DRY – a nice approach i’ve come across recently is demonstrated here: http://www.goeleven.com/blog/entryDetail.aspx?entry=59 The author extends a common implementation of the specification pattern to also include the ability to determine the unsatisfied part of the specification – returning the unsatisfied part as a specification itself. Good stuff! I can imagine it would be relatively painless to extend this to derive user-friendly failure reasons.

  • Juliano Nunes

    Is it possible to return which specs isn’t satisfied?

    • jbogard

      I don’t see why not. Just find where IsSatisfied = false