According to Fowler and Evans, Specification ” is to separate the statement of how to match a candidate, from the candidate object that it is matched against. As well as its usefulness in selection, it is also valuable for validation and for building to order “Â .
We might need to secify the state of an object for one of these three purposes.
- To validate an object to see if it fullfills some need or ready for some purpose (Validation)
- To select an object from a collection (Selection)
- To specify the creation of a new object to fit some need (Building to order)Â *Quote from DDD / Eric Evans*
Specifications in the implementation of Fowler and Evans are classes, that contain the logic of validation, in a more explicit way than a methods that hides inside a domain object.
Composite specifications are specifications with logical operations like “And” “Or” defined to build a composite of exression tree. These operation can be presented in a more Domain friendly manner like a  fluent interface where you can say for example Â
Spec1.And(Spec2).And(spec3.Not()) .
The problem is that building such a composite , domain friendly , expression tree can add really a lot of classes to the application (Specifications Hirarchy, Expression Builders for having Fluent Interfaces,… etc) .
Those who have been arround microsoft technologies lately, might heard about Linq and C# 3.0, read some articles about it. Unfortunaitly Linq is often missunderstood, as embedding Sql in the code, which is DEFINITLY NOT THE CASE, Linq is all based on expression trees, that are intrepreted by an implementation engine for producing the appropriate query.
I will not go in details into Linq’s use for data quering, but i ll try to demonstrate another use of linq’s expression trees, in making explecit, predicate-like simple composite specifications.
For the purpose of the demo, i ll make a small introduction of some C# 3.0 features i am using.
Extension Methods: Extension Methods are a syntaxic sugar, representing a special case of static methods to turn it more discoverable .
Example:
public static class Extensions
{Â Â Â public static bool IsNullOrEmpty(this string s)
   {
       return (s == null || s.Trim().Length == 0 );
   }
}
class Program
{
   static void Main( string[] args)
   {
       string newString = null;
       if (newString.IsNullOrEmpty())
       {
           // Do Something
       }
   }
}
so the “this” keyword in the parameters tells that this will be an extension method for all the object of this type. dont worry , no encapsulation is violated, extension methods have access only to public members.
Lambda Expressions: Lambda expression is a syntaxic sugar of the anonymous methods, for people that dont know delegates, delegates are method holders, u define a type of delegate by specifieng parameters and return types
like
delegate object DelegateName(object par1,objaect par2);
then you can anonymously make a delegate like so
DelegateName myDelegate= delegate(object par1,object par2){
   //do something here and return the delegates return type (object)
   return new object();
};
now u can call this delegate using its name mydelegate(obj1,obj2);
lambda expressions add even shorter syntax for defining the body of the anonymous method so u can for instance write
DelegateName myDelegate= (object par1,object par2)Â =>Â new object();
after this very brief introduction, i ll start implementing my very simple example of predicates:
first of all i ll define a delegate that will take a type T and returns a bool
delegate bool ObjectPredicateDelegate<T>(T arg);
now i can write
ObjectPredicateDelegate<Student> studentOver18= Student s => s.Age > 18 ;
that defines an anonymous method that is compiled on compile time, so it can be executed using the name “studentOver18″ and passing a student as a prameter, what i want is not method but an expression, lucky enough, Linq namespace has the Expression type so i can right
Expression<ObjectPredicateDelegate<Student>> studentOver18Expression = Student s => s.Age > 18 ;
you should be wondering what the deffirence is, this Epression is not compiled, it is deferred till the runtime, so id i want to execute it i should do
studentOver18Expression.Compile().Invoke(s);
moreover studentOver18Expression.ToString()Â will produce “s => s.Age >18″ cool isnt it?
now, i want to implement And and Or operations that produce the same delegate , where i can pass a student and get a boolean. These operations are already implemented by default in Linq namespace, but they return a BooleanExpression which is not really what i want, so i ll do mine using Extension methods
public static Expression<ObjectPredicateDelegate<Student>> And(this Expression<ObjectPredicateDelegate<Student>> exp1, Expression<ObjectPredicateDelegate<Student>> exp2){
          ParameterExpression p = Expression.Parameter(exp1.Parameters[0].Type, exp1.Parameters[0].Name);
             return (Expression<ObjectPredicateDelegate<Student>>)Expression.Lambda<ObjectPredicateDelegate<Student>>(
               Expression.And(Expression.Invoke(exp1,p), Expression.Invoke(exp2,p)), p);
}
now using this extension method i can write
Expression<ObjectPredicateDelegate<Student>> studentOver18Specification = Student s => s.Age > 18 ;
Expression<ObjectPredicateDelegate<Student>> studentUnder26Specification = Student s => s.Age < 26 ;
Expression<ObjectPredicateDelegate<Student>> studentYouthAgeSpecification = studentOver18Specification.And(studentUnder26Specification);
now we can continue implementing other operations like Or, Not… in the same manner.
I agree that ObjectPredicateDelegate<Student> is long to write each time , but we can use the “using” keyword to creat an alias
using StudentPredicateDelegate=ObjectPredicateDelegate<Student>
or even
using StudentPredicate=Expression<ObjectPredicateDelegate<Student>>
this way i can simplify the last code to look more friendly
StudentPredicate studentOver18Specification = Student s => s.Age > 18 ;
StudentPredicate studentUnder26Specification = Student s => s.Age < 26 ;
StudentPredicate studentYouthAgeSpecification = studentOver18Specification.And(studentUnder26Specification);
now studentYouthAgeSpecification.ToString() will produce    “s => (Invoke(s => (s.age > 18),s) And Invoke(s => (s.age < 26),s))”
i am not sure i ve been very clear, i ll try to post more examples soon :)


Good post. I especially love the fact that you demonstrate how to abstract the predicate (to a delegate) and then how to compose this abstraction using things like And. The only question I have is why use expression trees? Lambdas can be converted to either a delegate (invocable) or an expression tree (examinable). In the code, you only ever combine, compile, and invoke the lambdas so they could easily just be delegates; however, if you want to examine and then act on the structure of the lambda then it would be very compelling to store them as expression trees.
public static Predicate And(this Predicate p1, Predicate p2)
{
return x => p1(x) && p2(x);
}
Of course this definition would not be sufficient if I needed to examine the structure. So if I translated all ands *inside* of a lambda to calls to And then that would make a lot of sense. Because I am using expression trees to examine the contents of a lambda and then act on that (perhaps redefining it).
Comment by Wes Dyer — February 26, 2007 @ 7:00 pm
First of all thank you for your comment Wes :)
Your question of why to use expression trees makes sence in my example, but unfortunaitly i had to do it this way because i couldnt find a way to do it without invoking the precedent expressions.
what i would like to do (and i couldnt acheive), is to build an expression tree specification, that i can analyse in a factory for building an object (Building to order) , where true/false result result doesnt help much in that case .
Yes in my example i can still analyse the to string i get from ToString (analysing a string is far more limited than analysing a real full ExpresionTree)
So my aim was to build a Generic Specification that i can use for the all three specifications needs. If you have any suggestions, i ll be interested.
By the way, there are some types of Expressions that i didnt get , such as a Funclet, or a StrongCard (i am not sure about the name because i dont have Orcas at work :p)
And finally i would like to suggest an interface for all expressions that take two parameters, this way i can write
if(exp1 is TwoParameteredExpression){
//here i can get the parameters and the operation and analyse their types
}
well not absolutely a two parameters expression interface, but my suggestion is to group expressions in a way that ease analysing with less casting…
Comment by sadek — February 28, 2007 @ 10:32 am
So, are you saying that instead of using specifications, we should just use LINQ expressions as the specification, and have the LINQ expression be of the type Expression?
I was thinking about that too, and I am just curious if LINQ expressions can actually do away with having to write our own specification classes. It will eliminate code, but may also get rid of some of the expressiveness of the code. Specification classes can be a nice place to hold domain logic…just wondering out loud where we will hold these expressions so that they too can be reused.
– Tim
Comment by Tim McCarthy — March 26, 2007 @ 5:03 am
Personally, i dont guess you can reuse specifications themselvs. You might reuse there classes, but not themseleves… I guess that each specification belongs to one scenario, and cant be reused even if they look so (think of design by contrats and invariants–Spec# Research ).
For the expressiveness, doesnt it look expressive what I ve just wrote up? of course if we write all our specification in a one line, that will look rather unreadable, but dividing it into a predicate style makes it as expressive as a custom designed specifications. By the end, this technique doesnt guarantee readability suddenly and magically, so best practices are needed.
And if you need to extend it, it is as easy as defining extension methods, exactly as i did for the “And”.
I revisited the example, because i wasnt comfortable with the word “Invoke” repeated in the result of the ToString() , with the new implementation i used the internal Visitor class, to revisit parameters so that i will not get this ugly Invoke :) I can pass you the revised sample if interested.
Comment by sadek — March 26, 2007 @ 7:13 pm