Implementing the Specification Pattern in .NET

Apr 15, 2011 on .NET, Design Patterns

Recently I have been reading Eric Evans excellent book on Domain Driven Design. One of the patterns discussed in this book is the Specification Pattern, which was conceived by Eric Evans and Martin Fowler (see here for full description).

This pattern is about encapsulating domain rules into specification classes. These are then used to test if a particular domain object satisfies the criteria. Typically, they expose a public function called IsSatisifiedBy() that returns a boolean based on whether the object satisfies the specification.

For example, if we have a bank account value object…

publicclassBankAccount{publicintCurrentBalance(get;set;}}

..we may define a specification to test whether the bank is overdrawn…

The main advantage of this pattern is that any logical decisions within the code will be based upon language the customer would understand. It also makes the code more readable, which will benefit other developers when they need to understand the system.

An additional feature of this pattern is that the specifications can be ‘chained’ using boolean logic to create more complex specifications. Below is an example of this in action:

So, how do we implement this in .NET? Fortunately, generics and extension methods allow us to provide a set of classes that are flexible enough to meet the requirements of this pattern under most circumstances.

First of all, we should amend the ISpecification interface to be type safe by making it a generic interface:

That is all we need to do in order to implement this pattern in a reusable manor in .NET. I have attached a visual studio solution below that contains a class library implementing this pattern and a demonstration console application.