Tag Archives: Patterns

About the Specification pattern

A couple of days ago i mentionned Yves Goeleven’s blog as a reference for solutions using DDD principles. Let’s have a look at his implementation of the AndSpecification and OrSpecification in Design Patterns – The Specification Pattern – Part I:

class AndSpecification<t> : CompositeSpecification<t>
{
 public override bool IsSatisfiedBy(T candidate)
 {
  bool isSatisfied = true;
  foreach( ISpecification<t> spec in Specifications)
  {
   isSatisfied &= spec.IsSatisfiedBy(candidate);
  }
  return isSatisfied;
 }
}
class OrSpecification<t> : CompositeSpecification<t>
{
 public override bool IsSatisfiedBy(T obj)
 {
  bool isSatisfied = false;
  foreach( ISpecification<t> spec in Specifications)
  {
   isSatisfied |= spec.IsSatisfiedBy(obj);
  }
  return isSatisfied;
 }
}

I believe that it would be better if the implementations had the same lazy evaluation behaviour as the C# && and || operators. Eg: in C# one can write (a && b) and if a evaluates to false, then b is not evaluated anymore. Consider the following code:

if (person != null && person.Age > 18) { }

Let’s rewrite that same code using Specifications:

class NotNullSpecification<t> : ISpecification<t>
 where T : class
{
 public bool IsSatisfiedBy(T item)
 {
  return item != null;
 }
}

class OlderThanSpecification : ISpecification<person>
{
 private int age;

 public OlderThanSpecification(int age)
 {
  this.age = age;
 }

 public bool IsSatisfiedBy(Person person)
 {
  return person.Age > this.age;
 }
}

class PersonNotNullAndOlderThan18Specification : AndSpecification<person>
{
 public PersonNotNullAndOlderThan18Specification()
 : base(new NotNullSpecification<person>(), new OlderThanSpecification(18))
 {
 }
}

Using the mentionned AndSpecification implementation the following unittest will fail:

[TestMethod]
public void TestPersonNotNullAndOlderThan18Specification()
{
 Person person = null;

 ISpecification<person> specification = new PersonNotNullAndOlderThan18Specifictation();
 Assert.IsFalse(specification.IsSatisfiedBy(person));
}

In order to make that test pass we could rewrite the specifications as following:

public abstract class CompositeSpecification<t> : ISpecification<t>
{
 private readonly IEnumerable<ispecification<t>> specifications;

 public CompositeSpecification(IEnumerable<ispecification<t>> specifications)
 {
  this.specifications = specifications;
 }

 protected IEnumerable<ispecification<t>> Specifications
 {
  get { return this.specifications; }
 }

 abstract public bool IsSatisfiedBy(T item);
}

public class AndSpecification<t> : CompositeSpecification<t>
{
 public AndSpecification(IEnumerable<ispecification<t>> specifications)
  :base(specifications)
 { }

 override public bool IsSatisfiedBy(T item)
 {
  foreach (ISpecification<t> specification in this.Specifications)
  {
   if (!specification.IsSatisfiedBy(item))
   {
    return false;
   }
  }

  return true;
 }
}

public class OrSpecification<t> : CompositeSpecification<t>
{
 public OrSpecification(IEnumerable<ispecification<t>> specifications)
  : base(specifications)
 { }

 override public bool IsSatisfiedBy(T item)
 {
  foreach (ISpecification<t> specification in this.Specifications)
  {
   if (specification.IsSatisfiedBy(item))
   {
    return true;
   }
  }

  return false;
 }
}

Presenting a generic DiscreteValuesRange

Let me start with a real world example demonstrating the usefulness of a generic DiscreteValuesRange. Imagine that i run a grid computing business and my clients want to book capacity on the grid for a given period. Before their booking is approved, i have to verify that the client has contracts that allow him to use the system for each day of the booking period. Usually, such a check is implemented as following:

bool CheckEachDayIsCovered(Booking booking, Client client)
{
 DateRange periodToCheck = booking.Period;
 DateTime endOfTime = new DateTime(9999, 12, 31);

 DateTime dayToCheck = periodToCheck.Begin;
 while (dayToCheck <= periodToCheck.End)
 {
  bool dayIsCovered = false;

  foreach (Contract contract in client.Contracts)
  {
   if (contract.Period.Includes(dayToCheck))
   {
    dayIsCovered = true;

    if (contract.Period.End < endOfTime)
    {
     dayToCheck = contract.Period.End.AddDays(1);
    }
    else
    {
     return true;
    }
   }
  }

  if (!dayIsCovered)
  {
   return false;
  }
 }

 return true;
}

After a while clients want to buy licenses for only a couple of hours instead of a full day. I realise that my check can remain the same, but that the concept “EndOfTime” has become DateTime(9999, 12, 31, 23, 59, 59) and that i can advance only an hour instead of a day. Since i want to reuse my code i define the IDiscreteValueProvider<T> interface (See Discrete Space):

interface IDiscreteValuesProvider<t>
{
 T GetNextValue(T value);
 T MaxValue { get; }
}

After this i’m able to implement a DiscreteValuesRange<T> that implements the following interface (See: Generic Range):

interface IDiscreteValuesRange<t> : IRange<t>
{
 bool IsCoveredByRanges(IEnumerable<idiscreteValuesRange<t>> ranges);
}

Now, with all this infrastructure i can rewrite my original method as following:

bool CheckEachDayIsCovered(Booking booking, Client client)
{
 return booking.Period.IsCoveredByRanges(client.GetContractPeriods());
}

class Client
{
 ...
 IEnumerable<range<dateTime>> GetContractPeriods()
 {
  foreach (Contract contract in this.Contracts)
  {
   yield return contract.Period;
  }
 }
}

Feel free to download all this infrastructure: DiscreteRange.zip and use it for your next coverage check.

Presenting a generic EffectivityManager

I’ve already presented a Generic Effectivity. Offcourse, managing all these effectivities (versions of data) can be handled in a generic way too. A bit of experience mixed with Patterns for things that change with time allowed me to come up with the following interface:

public interface IEffectivityManager<t> : IList<ieffectivity<t>>
{
 IEffectivity<t> Add(T t, DateTime begin);
 IEffectivity<t> GetSnapshot(DateTime validityDate);
 bool TryGetSnapshot(DateTime validityDate, out IEffectivity<t> effectivity);
}

Feel free to download IEffectivityManager.txt, EffectivityManager.txt and EffectivityManagerTester.txt.

Presenting a generic Effectivity

Very often we have to manage objects and their changes over time. Usually we implement this by adding a Range<DateTime> to the data. Martin Fowler has a name for this pattern: Effectivity and i have an implementation for the following interface:

public interface IEffectivity<t> : IComparable<ieffectivity<t>>
{
 T Element { get; }
 IRange<dateTime> ValidityPeriod { get; }
 bool IsEffectiveOn(DateTime validityDate);
}

Feel free to download IEffectivity.txt, Effectivity.txt and EffectivityTester.txt.

Presenting a generic Range

Quite often i’m writing code that compares one value against a range of other values. Most implementations compare the value against the boundaries (smallest and largest in the collection of other values). Having written this sort of code way too much i’ve decided to generalize the problem and distill an interface:

public interface IRange<t>
{
 T Begin { get; set; }
 T End { get; set; }
 bool Includes(T t);
 bool Includes(IRange<t> range);
 bool Overlaps(IRange<t> range);
}

Offcourse, i’ve also written implementation ;) Feel free to download IRange.txt, Range.txt and RangeTester.txt