Wednesday, March 25, 2009

"Not" Specification

I am currently spiking out a DDD based solution that will have a significant amount of rules associated. I am currently making heavy use of the Specification pattern as there is a tonne of reuse from these and potentially a more readable API. One problem I have and have always had with the typical Specification pattern is the Not() method; It is a bit ugly and when used in method chaining is somewhat confusing as the Not is a suffix, unlike the other methods in the fluent interface (And and Or).

I have made a slight change to my base specification class by adding an AndNot(x) method as I quite frequently am finding the need for it and it is so much more readable than And(x).Not().

This is simply an addition of the signature on the interface:

public interface ISpecification
{
bool IsSatisfiedBy(T candidate);

ISpecification And(ISpecification other);

ISpecification AndNot(ISpecification other);//NEW!!!

ISpecification Or(ISpecification other);

ISpecification Not();
}

and the implemented code is just:

public ISpecification AndNot(ISpecification other)
{
return new AndSpecification(this, new NotSpecification(other));
}


I don't see a need to remove the Not() as it is still useful in defining reusable not specs.

HTH
Rhys

No comments: