Thursday, September 1, 2011

how to aggregate LinqSpecs specifications

Kar-Khan wrote a means to spool up LinqSpec specifications today which is something we have been struggling with. Here is his class:

using LinqSpecs;

namespace AMD.Avalanche.Core.Utils

{

   public class SpecificationBuilder<T>

   {

      private Specification<T> _masterSpec;

      

      public SpecificationBuilder() { }

      

      public void AddAnd(Specification<T> specification)

      {

         if (_masterSpec == null)

            _masterSpec = specification;

         else

            _masterSpec = new AndSpecification<T>(_masterSpec, specification);

      }

      

      public Specification<T> ToSpecification()

      {

         return _masterSpec;

      }

   }

}

 
 

How to use it: In...

var specBuilder = new SpecificationBuilder<Foo>();

specBuilder.AddAnd(new AdHocSpecification<Foo>(
p => p != null));

var bar = specBuilder.ToSpecification();

 
 

p => p != null is an example of a Specification<Foo> that may be shaped like so:

public static Specification Sanity(Boolean isOk)

{

   var isSane = new AdHocSpecification(p => p.IsOk == isOk);

   return isSane;

}

 
 

...and handed in like so:

var specBuilder = new SpecificationBuilder<Foo>();

specBuilder.AddAnd(new AdHocSpecification<Foo>(WebProgramSpecs.Sanity(true)));

var bar = specBuilder.ToSpecification();

No comments:

Post a Comment