Archive

Archive for the ‘SOLID’ Category

Principles of Programming

January 20, 2012 1 comment

Great video tutorial about principles of programming.

Principles of Programming Part 1

Principles of Programming Part 2

Happy Clean Coding !!!

Why program against an interface ?

July 19, 2011 8 comments

I have done a lot of post regarding interface based programming and we have seen some good benefits of programming against an interface as compare to its concrete implementation. One of the best things it does it that it promotes SOLID design principles and allows us to have a level of abstraction or separation of concerns.

If you haven’t read my previous post about the benefits of interface I recommend reading them and here are some of those posts.

In this post I am going to show another benefit of using interfaces and that is how easy it is to add additional behavior (decorators) without changing the code. With interfaces you are able to provide nice extensibility point and keeping our code SOLID ( yes it is the big ‘O‘ in SOLID) and as usual Dependency Injection plays a key role in accomplishing the task with minimal effort.

Let’s start with a simple interface like this one.

ICustomerRepository.cs


public interface ICustomerRepository
{
   List<Customer> GetCustomers();
}

And let’s write the CustomerRepository class which implements this interface.

public class CustomerRepository : ICustomerRepository
{
   public List<Customer> GetCustomers()
   {
      return new List<Customer>
                {
                   new Customer(1, "Joe", "Blogg"),
                   new Customer(2, "John", "Doe")
                };
   }
}

And this is our client code that calls the CustomerRepository class, it’s a standard example I have used in most of my posts depicting a real world example of business layer calling the repository layer.

CustomerBl.cs

public class CustomerBl : ICustomerBl
{
   private readonly ICustomerRepository _customerRepository;
   public CustomerBl(ICustomerRepository customerRepository)
   {
      _customerRepository = customerRepository;
   }

   public List<Customer> GetCustomers()
   {
      return _customerRepository.GetCustomers();
   }
}

I will add a simple class diagram for people who love to see the class diagram,as I personally favor class diagram over code.

Customer Repository Injected into Customer Business Layer

As you can see nothing special, we are just using constructor injection in our CustomerBl so that through IoC I can decide which class will be injected into the CustomerBl as long as the class implements the ICustomerRepository interface (contract).

So far so good the code is running fine and it’s in production, your customer is happy and you feel good about it.

After some time the customer says that I want to do logging when this function is called and the first thing which comes to your mind is okay I will write a logging code in the CustomerRepository GetCustomers() method.

But wait lets put some thought into this. First as soon as you are modifying the CustomerRepository class you are breaking the Single Responsibility Principle as this class has now 2 reasons to change.

  • If the GetCustomers() method logic changes
  • If the logging mechanism changes

Lets think “does this logging really the CustomerRepository’s responsibility” and at the same time we don’t want to put the logging code into CustomerBl class as it’s not even its responsibility. And what about the logging it could change in the future.

So let’s abstract the logging responsibility into its own interface like this.

ILogger.cs

public interface ILogger
{
   void Log(string message);
}

And the class which implements this interface is

DebugLogger.cs

public class DebugLogger : ILogger
{
   public void Log(string message)
   {
      Debug.WriteLine(message);
   }
}

Here I have chosen a simple class which writes to the output window to keep the example as simple as possible and since we are implementing through interface we can easily change it into file based or database based logger using the Dependency Injection Principle.

Here is the interesting part as you can see from our ICustomerRepository interface that the CustomerBl class just care for this interface and has no knowledge of what the actual class does.

This gives us a good opportunity to implement a new class which has the same interface signature but does the logging and then calls our actual CustomerRepository class as is. With this philosophy nothing has changed and the new class would act as a proxy.

Hmmm let me show you the code and see if I can make more sense so I will create a new class called LogCustomerRepository which will implement the ICustomerRepository interface and will have dependency on it as well as on the ILogger interface.

LogCustomerRepository.cs

public class LogCustomerRepository : ICustomerRepository
{
   private readonly ICustomerRepository _customerRepository;
   private readonly ILogger _logger;
   
  public LogCustomerRepository(ICustomerRepository customerRepository,
         ILogger logger)
   {
      _customerRepository = customerRepository;
      _logger = logger;
   }

   public List<Customer> GetCustomers()
   {
      _logger.Log("Before the get customer method");
      var result = _customerRepository.GetCustomers();
      _logger.Log(string.Format("Total results found {0}", result.Count));
      return result;
   }
}

And an elaborated class diagram.

Log Customer Repository Injected into Customer Business Layer

Customer Repository Injected into Log Customer Repository
So as you can this class just decorates the CustomerRepository and it shouldn’t make any difference to the client code(CustomerBl) as both the class implement the same interface (contract).

Now only thing left is wire this up in our IoC and I am going to use Castle Windsor Installer to have a nice separation of the configuration from the actual container.

If you are not familiar with Castle Windsor installer class please read my previous post about it.

CustomerInstaller.cs

public class CustomerInstaller : IWindsorInstaller
{
   public void Install(IWindsorContainer container,
                       IConfigurationStore store)
   {
      container.Register(
         Component.For<ILogger>()
            .ImplementedBy<DebugLogger>(),

         Component.For<ICustomerRepository>()
            .ImplementedBy<CustomerRepository>(),

         Component.For<ICustomerRepository>()
            .ImplementedBy<LogCustomerRepository>()
            .Named("LogCustomerRepository"),

         Component.For<ICustomerBl>()
            .Named("CustomerBl")
            .ImplementedBy<CustomerBl>()
            .ServiceOverrides
            (
               ServiceOverride
                  .ForKey("customerRepository")
                  .Eq("LogCustomerRepository")
            )
      );
   }
}

This is the core of how registration and components works in Castle Windsor. The important thing to notice here is I am using named component registration as I want to make sure that when my CustomerBl class asks CastleWindsor to resolve for an implementation of type of ICustomerRepository it will return the LogCustomerRepository class instead of CustomerRepository and this way I am making sure that the decorators are invoked in the right order.

So in the ServiceOverrides method I am telling CastleWindsor that CustomerBl has a Dependency on ICustomerRepository and the name of the variable which is passed into the constructor is “customerRepository” and when you come across this variable then invoked the registered component which has been tagged as “LogCustomerRepository” rather than the default registered component CustomerRepository.

Although this syntax is very specific to Castle Windsor but the concept is quite uniform across all the IoC containers.

Let’s write a unit test to see how this all comes together.

UnitTest.cs

[TestClass]
public class When_using_CustomerBl
{
   private IWindsorContainer _container;
   [TestInitialize]
   public void Setup()
   {
      _container = new WindsorContainer();
      _container.Install(new CustomerInstaller());
   }

   [TestMethod]
   public void Should_be_able_to_get_customers()
   {
      var customerBl = _container
                        .Resolve<ICustomerBl>
                        ("CustomerBl");

      var result = customerBl.GetCustomers();
      Assert.IsTrue(result.Count > 0);
   }
}

And when I run the test it passes with the desired result and in the output window I do see the messages I expect.

Unit Test

As you can see from the Watch window that how these interfaces are resolved by Castle Windsor and how I am getting the correct type when I need it.

This way of decorating interfaces and creating decorators is a nice and easy pattern but it also gives us some insight into Aspect Oriented Programming as these decorators are merely cross cutting aspects.

For example we can easily create Logging,Security,Caching,Instrumentation etc decorators and Inject them with Castle Windsor.

Advertisement

Writing Rule Specification for the Composite Pattern

In the last post we build a nice fluent interface to use composite pattern with Linq Expression. The idea was to use composite pattern to chain these conditions (specification) and Linq helped us a lot in accomplishing that.

We also unit tested some of these expression to see how the linq expression are built for And,Or, Not conditions and had that flexibility to apply them using lambada expression.

So in this post I will show you how we should write these specification like a rule specification to mimic a real life application.

As a good designed of any framework or API our main goal is to hide the inner complexity and workings from consuming code and try to expose them with easy interfaces and write some unit test to show how these API’s will be consumed.

Lets look at the employee class we created in our previous post and build some rule specifications.

Employee.cs

public class Employee
{
   public int Id { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public virtual IList<Address> Address { get; set; }
}

And say the rule specifications for granting a leave are as follows :-

  • If an employee has an address then he/she is preferred for taking a leave
  • If an employee’s First Name starts with the letter ‘T’ then they are considered highly experienced
  • And an employee satisfies the above 2 condition then only they can take a leave

I know these rules sounds really ridiculous but I just wanted to show the gravity of the rules, as I have always seen developers complaining that they couldn’t write a Clean Code or SOLID code because the business rules were way too complex and weird, or the client couldn’t make up their mind and kept on chopping and changing.

Yes I have faced the same situation before and in my opinion it is these confusing complex rules and inadequate unit test are the main culprit of bad design and failure of a system.Anyway that’s my personal opinion and let’s get back to writing these specification.

Employee Rule Specification

public class EmployeeRuleSpecification
   {
      public CompositionWithExpression<Employee> IsPreferred
      {
         get
         {
            return new CompositionWithExpression<Employee>
               (
                  e => e.Address.Count > 0
               );
         } 
      }

      public CompositionWithExpression<Employee> IsExperienced
      {
         get
         {
            return new CompositionWithExpression<Employee>
               (
                  e => e.FirstName.StartsWith("T")
               );
         } 
      }

      public CompositionWithExpression<Employee> And(
                     CompositionWithExpression<Employee> other)
      {
         return 
            new CompositionWithExpression<Employee>
                                    (
                                       other.Predicate
                                    );
      }

      public ISpecificationWithExpression<Employee> PreferredAndExperienced
      {
         get
         {
            return (
                     this.IsPreferred.And(this.IsExperienced)
                   );
         }
      }
   }

[Pardon my indentation as I wanted to fit the long names and parameters with in the code box.]

So here what we have done is we have moved the responsibility of specifying the rules into its own class and which is good design practice (Single Responsibility Principle) and also the code looks very neat.

First If I am working on a huge project with the above code I don’t have to crawl though 1000 line to find out what this if else condition is trying to do.

Second if the rules changes or more rules need to be added I have to change only this class and that too because of the specification interface I am just adding a new specification and using composition compose a complex(compound) business rules.

Third important thing is that since I can do isolation testing on each expression as well as compound condition, I don’t have to go through 1000 lines of debugging to find out what condition is being invoked by the current state of the employee object. Otherwise we all have heard this thing “why it works in dev environment but fails in production” etc.

Lets plug this into our original Employee class by adding a new method CanTakeLeave.

public class Employee
   {
      public int Id { get; set; }
      public string FirstName { get; set; }
      public string LastName { get; set; }

      public virtual IList<Address> Address { get; set; }

      public bool CanTakeLeave()
      {
         var specification = new EmployeeRuleSpecification();
         return specification.IsExperienced
                             .And(specification.IsPreferred)
                             .IsSatisfiedBy(this);
      }
   }

As you can see the class still looks neat and compact and there is no ugly if/else/switch etc.Lets write a unit test to see how this method will be called and test what result are expected under what circumstances.

UnitTest.cs

[TestClass]
public class When_using_Employee_Rule_Specification
{
   [TestMethod]
   public void Should_be_able_to_take_leave()
   {
      var employee = BuildData.GetEmployeeWithAddress();
      var result = employee.CanTakeLeave();

      Assert.AreEqual(true, result);
   }
}

As you can see for this test to verify correctly I am calling the GetEmployeeWithAddress static on the static BuildData class which return an employee with his/her address and in this case my test passes with flying colors.

I hope this post will help you write complex specification and rules for a real life project as you can specify any number of these rules specification and compose them together to build complex rules.

Last but not the least is if you like you can this further and decouple the dependency of rule specification object and the business object i.e pass an interface to your business object, something like this.

public class Employee
{
   public int Id { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public virtual IList<Address> Address { get; set; }

   public Employee(IEmployeeRuleSpecification employeeRuleSpecification)
   {

   }
}

and then you can use Dependency Injection to inject the rule specification which you might have boot strapped it your project.( May be I should leave that up to you guys 😉 )

Composite Pattern using Linq Expressions

I hope you guys have enjoyed by previous posts on Specification Pattern and the Composition Pattern as this post is an extension to those post and I recommend you read those post before you read this one.

Composition Pattern

Specification Pattern

In this post I am going to take both patterns and apply some Linq expression as I always try to refactoring code and improve coding style every time I get a chance.

In the Specification Pattern post we started with a simple interface ISpecification as following:

ISpecification.cs

public interface ISpecification<T>
{
bool IsSatisfiedBy(T candidate);
ISpecification<T> And(ISpecification<T> other);
ISpecification<T> Or(ISpecification<T> other);
ISpecification<T> Not();
}

And this interface is the core of the Composition Pattern so lets modify this interface so that we can use the Linq Expression provided by .NET.

ISpecificationWithExpression.cs

public interface ISpecificationWithExpression<T>
{
Expression<Func<T, bool>> Predicate { get; }
bool IsSatisfiedBy(T candidate);
ISpecificationWithExpression<T> And(ISpecificationWithExpression<T> other);
ISpecificationWithExpression<T> Or(ISpecificationWithExpression<T> other);
ISpecificationWithExpression<T> Not();
}

The idea is that we are going to use Linq Expression and its internal expression building logic to chain our conditions and because we are using Expression<Func<T, bool>> we can specify our criteria (condition) as a lambada Expression.

Lets move on and first implement the interface to see how our code structure looks like, I always prefer it this way so that I can see the bigger picture without getting into implementation specifics.

public class CompositionWithExpression<T> : ISpecificationWithExpression<T>
{
public Expression<Func<T, bool>> Predicate { get { } }

public bool IsSatisfiedBy(T candidate)
{

}

public ISpecificationWithExpression<T> And(ISpecificationWithExpression<T> other)
{

}

public ISpecificationWithExpression<T> Or(ISpecificationWithExpression<T> other)
{

}

public ISpecificationWithExpression<T> Not()
{

}
}

So this gives us a base structure of our class and now all what we have to do is implement the And(), Or() and the Not() methods using Linq Expressions and its compositions.

CompositionWithExpression.cs

public class CompositionWithExpression<T> : ISpecificationWithExpression<T>
{
private readonly Expression<Func<T, bool>> _predicate;

public CompositionWithExpression(Expression<Func<T, bool>> predicate)
{
_predicate = predicate;
}

public Expression<Func<T, bool>> Predicate
{
get { return _predicate; }
}

public bool IsSatisfiedBy(T entity)
{
return _predicate.Compile().Invoke(entity);
}

public ISpecificationWithExpression<T> And (ISpecificationWithExpression<T> other)
{
var otherInvoke = Expression.Invoke( other.Predicate, 
this._predicate.Parameters);

var newExpression = Expression.MakeBinary(ExpressionType.AndAlso, 
_predicate.Body, otherInvoke);

return 
new CompositionWithExpression<T>(Expression.Lambda<Func<T, bool>>
(newExpression, 
_predicate.Parameters));
}

public ISpecificationWithExpression<T> Or(ISpecificationWithExpression<T> other)
{
var otherInvoke = Expression.Invoke(other.Predicate, 
this._predicate.Parameters);

var newExpression = Expression.MakeBinary(ExpressionType.OrElse, 
_predicate.Body, otherInvoke);

return 
new CompositionWithExpression<T>(Expression.Lambda<Func<T, bool>>
(newExpression, 
_predicate.Parameters));
}

public ISpecificationWithExpression<T> Not()
{
var negateExpression = Expression.Lambda<Func<T, bool>>
(Expression.Not(_predicate.Body), 
_predicate.Parameters);

return new CompositionWithExpression<T>(negateExpression);
}
}

So far what we have done is that we have combined Lambada Expression based on method operation like Or,And and Not.

Lets write some unit test and see how we can use lambada expression to specify the condition.

[TestClass]
public class When_using_Specification_With_Expression
{
[TestMethod]
public void Should_be_able_to_invoke_or_condition()
{
var employee = BuildData.GetEmployee;

var specification = new CompositionWithExpression<Employee>
(e => e.FirstName.StartsWith("T"));

var anotherSpecification = new CompositionWithExpression<Employee>
(e => e.Address.Count > 0);

var newExpression = specification.Or(anotherSpecification);

Assert.AreEqual(true, newExpression.IsSatisfiedBy(employee));
}

[TestMethod]
public void Should_be_able_to_invoke_an_and_condition()
{
var employee = BuildData.GetEmployee;
employee.Address = BuildData.GetAddress;

var specification = new CompositionWithExpression<Employee>
(e => e.FirstName.StartsWith("T"));

var andSpecification = new CompositionWithExpression<Employee>
(e => e.Address.Count > 0);

var compositeSpecification = specification.And(andSpecification);
Assert.AreEqual(true, compositeSpecification.IsSatisfiedBy(employee));
}

[TestMethod]
public void Should_be_able_to_invoke_a_not_condition()
{
var employee = BuildData.GetEmployee;
employee.Address = BuildData.GetAddress;

var specification = new CompositionWithExpression<Employee>
(e => e.FirstName.StartsWith("T"));

var negateSpecification = specification.Not();
Assert.AreEqual(false, negateSpecification.IsSatisfiedBy(employee));
}

}

and this is how the employee class looks like

public class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual IList<Address> Address { get; set; }
}

As you can see by the virtue of the fact that the CompositionWithExpression takes a Expression<Func<T, bool>> as constructor parameter,I can pass a lambada expression to specify the condition and it’s so easy to understand.

I think this has been a very lengthy post in terms of code so I will break it up into another post where I will revisit creating different specification and chain them in our entity class the way we did it for Customer class in the Composition Pattern post.

Composite Pattern

June 5, 2011 11 comments

This post is continuation of my previous post on Specification Pattern and in this post we will see how we can chain these Specifications (the interface) to build more complex rule with help of Composition.

First lets see the pattern statement

The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to “compose” objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.

The reason why we choose composition is that the interface we define in our Specification looks like a Predicate i.e. it takes an object as argument and returns a Boolean so if we chain multiple specification together it should still return a Boolean i.e. multiple specification can be together to yield whether the compound condition is true or not.

Lets look at three possible ways to combine these condition :-

  1. And Specification
  2. Or Specification
  3. Not Specification

And lets add the above three specification to our ISpecification interface we created in the Specification Pattern post.

public interface ISpecification<T>
{
    bool IsSatisfiedBy(T candidate);
    ISpecification<T> And(ISpecification<T> other);
    ISpecification<T> Or(ISpecification<T> other);
    ISpecification<T> Not();
}

Now you can see how we are composing things together, in the interface since all the other specification have the same signature and the same return type we can combine them together without breaking the contract(interface) and this is the core principle of Composite Pattern.

Lets write a class which will implement this interface and will help us compose specifications.

public abstract class CompositeSpecification<T> : ISpecification<T>
{
    public abstract bool IsSatisfiedBy(T candidate);

    public ISpecification<T> And(ISpecification<T> other)
    {
        return new AndSpecification<T>(this, other);
    }

    public ISpecification<T> Or(ISpecification<T> other)
    {
        return new OrSpecification<T>(this, other);
    }

    public ISpecification<T> Not()
    {
        return new NotSpecification<T>(this);
    }
}

The important thing is that since the class has been designed using Generics it can be applied to any class. Lets write code for each of these Condition Specification.

public class AndSpecification<T> : CompositeSpecification<T>
{
    private readonly ISpecification<T> left;
    private readonly ISpecification<T> right;

    public AndSpecification(ISpecification<T> left, ISpecification<T> right)
    {
        this.left = left;
        this.right = right;
    }

    public override bool IsSatisfiedBy(T candidate)
    {
        return left.IsSatisfiedBy(candidate) && right.IsSatisfiedBy(candidate);
    }
}
public class NotSpecification<T> : CompositeSpecification<T>
{
    private readonly ISpecification<T> other;

    public NotSpecification(ISpecification<T> other)
    {
        this.other = other;
    }

    public override bool IsSatisfiedBy(T candidate)
    {
        return !other.IsSatisfiedBy(candidate);
    }
}
public class OrSpecification<T> : CompositeSpecification<T>
{
    private readonly ISpecification<T> left;
    private readonly ISpecification<T> right;

    public OrSpecification(ISpecification<T> left, ISpecification<T> right)
    {
        this.left = left;
        this.right = right;
    }

    public override bool IsSatisfiedBy(T candidate)
    {
        return left.IsSatisfiedBy(candidate) 
                  || right.IsSatisfiedBy(candidate);
    }
}

Lets visualize it in a class diagram and see all the code we have written so far.

Composite Pattern

Lets modify the ApplicationLoanSpecification class we created in the previous post to implement the CompositePattern class.

public class ApplicantLoanSpecification : CompositeSpecification<Applicant>
{
    public override bool IsSatisfiedBy(Applicant candidate)
    {
        return (candidate.CreditRating == 10 && candidate.TotalEquity > 45000);
    }
}

So far nothing has change drastically and now we will start creating some more specifications.

public class SalarySpecification : CompositeSpecification<Applicant>
{
    public override bool IsSatisfiedBy(Applicant candidate)
    {
        return (candidate.Salary > 100000);
    }
}
public class AgeSpecification : CompositeSpecification<Applicant>
{
    public override bool IsSatisfiedBy(Applicant candidate)
    {
        return (candidate.Age < 80);
    }
}

So here I just created some fictitious conditions to create a real life complex business rules, the important thing is that because of using the pattern each of my class are very small and very specific(pardon the pun). And it’s another good example of Single Responsibility principle.Lets put it all together in our Applicant class and see how the method chaining looks like.

public class Applicant
{
    public Int32 Id { get; set; }
    public Int32 Age { get; set; }
    public Int32 CreditRating { get; set; }
    public decimal TotalEquity { get; set; }
    public decimal Salary { get; set; }

    private readonly ISpecification<Applicant> isQualifiedForLoan;
    private readonly ISpecification<Applicant> salaryIsQualified;
    private readonly ISpecification<Applicant> ageIsLessthanEighty;

    public Applicant()
    {
        isQualifiedForLoan = new ApplicantLoanSpecification();
        salaryIsQualified = new SalarySpecification();
        ageIsLessthanEighty = new AgeSpecification();

    }
    public bool CanApplyForLoan()
    {
        var canApplyForLoan = isQualifiedForLoan.
                               And(salaryIsQualified.
                               And(ageIsLessthanEighty));

        return canApplyForLoan.IsSatisfiedBy(this);
    }
}

You can see how our applicant business object encapsulates the business logic but have a nice separation of concern with these specifications. Also you might have noticed that the method chaining is done through a fluent interface.The whole condition can be read as “Is Qualified for Loan and Salary is qualitified and Age is less than Eighty”.

Lets see how we will invoke our applicant class from outside and I know I should have written a unit test, but hey its a blog post and sometimes even I feel lazy ;-).

static void Main(string[] args)
{
    var applicant = new Applicant()
                        {
                            Salary = 150000,
                            Age = 25,
                            CreditRating = 10,
                            TotalEquity = 55000
                        };

    Console.WriteLine("Can apply for loan:{0}",applicant.CanApplyForLoan());
    Console.ReadKey();
}

And when we run the program we get a true result as this applicant instance does satisfy all the conditions.I encourage you to get a full depth of this concept and try experiment with other Specification like the “Or” and “Not”. If you have any problem understanding or chaining other specification please feel to get in touch with me.

Last but not the least if you are designing any layered application/core framework for your application,it will be great if you can provide a nice fluent interface to other programmers.

Specification Pattern

May 22, 2011 5 comments

In this post I am going to show you what is a specification pattern and you will see how this pattern is so simple but yet so powerful and useful. This pattern is not part of the Gang of Four Pattern and was proposed by Martin Fowler and Eric Evans. The paper can be found here and I recommend to read it as the entire website is a great source of design patterns .

Anyway this is statement that Martin Fowler and Eric Evans stated in the paper.

The central idea of 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.

Yes I agree that statement is too abstract and I need to show some code before we enter into the world of specification pattern.

public interface ISpecification
{
    bool IsSatisfiedBy(object candidate);
}

Aha so this is a simple interface which talks about how a candidate(entity) can be plugged in and the class which implements this interface will specify the satisfying condition for that candidate(entity).

This is again a good example of SOLID programming as we are seeing Interface, Separation of Concern and Single Responsibility Principle hmmm so far so good lets dig deeper.

Suppose you are building a loan approval application and the business rules states that a customer can apply for loan if a customer has good credit rating and have an equity more than $ 45,000.

Generally when we start writing a code in a hurry or not using good design principles we will be tempted either to put this business rule directly in our UI layer or in the Applicant entity. With out thinking that very soon this simple “if else” logic can grow complex and will have a code smell in which ever place we write, as there is no separation of concern and both the class(either UI or Entity ) will have more than one reason to change if had to change the business rules.

Now we know what the problem is and lets apply the pattern in practice to simplify the problem.So I will use the interface signature and use some generics to make it more sophisticated.

ISpecification.cs

public interface ISpecification<T>
{
    bool IsSatisfiedBy(T candidate);
}

As you can see using generics makes this interface much reusable and can be used for any class.Lets implement the specification class first

ApplicantLoanSpecification.cs

public class ApplicantLoanSpecification : ISpecification<Applicant>
{
    public bool IsSatisfiedBy(Applicant candidate)
    {
        return (candidate.CreditRating == 10 && candidate.TotalEquity > 45000);
    }
}

As you can see now we have a nice separation of concern and we have wrapped the condition logic(specification) into its own class.

Application.cs

public class Applicant
{
    public Int32 Id { get; set; }
    public Int32 Age { get; set; }
    public Int32 CreditRating { get; set; }
    public decimal TotalEquity { get; set; }
    private readonly ApplicantLoanSpecification isQualitifiedForloan;

    public Applicant()
    {
        isQualitifiedForloan = new ApplicantLoanSpecification();
    }
    public bool CanApplyForLoan()
    {
        return isQualitifiedForloan.IsSatisfiedBy(this);
    }
}

This is how the class diagrams looks like.

Specification Pattern - Applicant Class Diagram

As you can see the Applicant Entity just invokes the Loan Specification class and calls IsSatisfiedBy method now our Applicant class has just one responsibility and we are not coding the “if else” logic inside this class.

If in the future we need to change the business rule we will be changing the ApplicantLoanSpecification class and build the complex logic inside the class.Rest of the method signature (the contract) and the implementation remains the same and it also promotes less code smell, clean code and unit testing.

In the next post I’ll talk about Composition Pattern which will help us combine and chain specification pattern into a compound specification so that we can build complex business rules with out polluting the code and promote the practice of writing “Clean Code”.

Decorator Pattern

February 16, 2011 6 comments

Continuing with my post with design patterns today I am going to talk about another useful design pattern called thedecorator pattern. This pattern like the Adapter pattern is very simple and quite useful. Lets see the definition of decorator pattern in wikipedia.

  In object-oriented programming, the decorator pattern is a design pattern that allows   new/additional behavior to be added to an existing object dynamically.

That’s pretty good as we are always trying to build software which are loosely coupled, highly extensible and flexible and this pattern will help us a lot in achieving our goals.

As usual we will start with a UML class diagram then we will understand what role each class in the pattern and then start writing some code

Decorator Pattern UML Class Diagram

And the role of each classes in this pattern are:

  • Component: This is the class which defines the interface to which we want to add behavior.
  • Concrete Component:: The actual class which implements the interface and has the attribute to which we want to add more behavior/decorators.
  • Decorator: The class which acts as glue between the concrete component and the behavior.
  • Concrete Decorator: The actual decorator which adds that behavior.

Well you might be wondering what the heck it all means and how I am going to build something which has a decorator pattern in it. Well lets start with a domain problem, lets say you have Product Repository class which brings a list of Products and lets see how it all looks in the class diagram.

A Product Repository class diagram

No surprises there and lets see the code before we start re factoring and implementing the decorator pattern.

IProductRepository.cs

namespace NoPattern
{
    public interface IProductRepository
    {
        IEnumerable<Product> GetAll();
    }
}

Product.cs

namespace NoPattern
{
    public class Product
    {
        public int Id { get; set; }
        public String Name { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
    }
}

ProductService.cs

namespace NoPattern
{
    public class ProductService
    {
        private IProductRepository _productRepository;

        public ProductService(IProductRepository productRepository)
        {
            _productRepository = productRepository;
        }

        public IEnumerable<Product> GetAll()
        {
            var products = _productRepository.GetAll();
            return products;
        }
    }
}

Well looks pretty good and does it jobs we have nice separation of concern (SOC) and good interface dependencies and constructor injection, all in all simple and easy code. But lets say one of the requirements by the business is that the price of the product must apply some discount and also an exchange rate needs to be applied for selling the product on other countries. At this point you might say lets modify the ProductRepository class and add that.But doing this you are violating the Open/Close principle of the SOLID principles and really it is not your repository class responsibility to handle this.

Well then you might say we will change it through a stored procedure to do that and which is not a good idea as we are seeing the trend is moving more towards Domain Driven Development and we don’t want to go backwards.

Lets break down the problem so that we can find a better solution, as we know that Product class has got some attributes and most of them are straight forward and may have one to one representation in terms of the data and how it is persisted,however it’s one attribute which is Price which needs some sort of behaviour or decoration depending on certain conditions.

That’s a good start and in order to add flexibility we convert this into an interface. If you remember some of my design patterns blogs one of the easiest way to club up disparate objects or behaviour is using an interface.

So lets define a simple interface IPrice which encapsulates the Price/Cost attribute of the Product class.

IPrice.cs

namespace DecoratorPattern
{
    public interface IPrice
    {
        Decimal Cost { get;set; }
    }
}

So what we are saying with this interface is that as long as there are classes which implement this interface can act and change (decorate) this property . I know this sounds a bit confusing and time to see some more code to understand the bigger picture. First I will show you how the Product class looks like.

Product.cs

namespace DecoratorPattern
{
    public class Product
    {
        public int Id;
        public String Name;
        public string Description;

        public IPrice Price { get; set; }
       
    }
}

This is the moment where you can see rather than just writing some code we are moving more into engineering a solution. So here in the product class we have created a hook for this interface so that we can latch other classes which have the same interface and it’s these other classes(the decorators) which can change/manipulate the attribute or the behaviour. Lets see how is that achievable in code.

CurrencyPriceDecorator.cs

namespace DecoratorPattern
{
    public class CurrencyPriceDecorator : IPrice
    {
        private IPrice _basePrice;
        private decimal _exchangeRate;

        public CurrencyPriceDecorator(IPrice price,decimal exchangeRate)
        {
            _basePrice = price;
            _exchangeRate = exchangeRate;
        }

        public decimal Cost
        {
            get { return _basePrice.Cost * _exchangeRate; }
            set { _basePrice.Cost= value; }
        }
    }
}

 

TradeDiscountPriceDecorator.cs

namespace DecoratorPattern
{
    public class TradeDiscountPriceDecorator : IPrice
    {
        private IPrice _basePrice;

        public TradeDiscountPriceDecorator(IPrice iPrice)
        {
            _basePrice = iPrice;
        }

        public decimal Cost
        {
            get { return _basePrice.Cost * 0.95m; }
            set { _basePrice.Cost = value; }
        }
    }
}

Wow this looks cool as you can see we are getting nice code and good separation of concerns.Of course I have hard corded some of the mathematical calculation for easy illustration and can be easily wrapped with the strategy pattern to apply what kind of calculation(strategy) to apply for which class.

Anyway so far looks good and lets see how we are going to create the decoration code and as most of you have guessed it right it is using the extension method, in fact you can easily say that extension method is .NET’s implementation of decorator pattern from a framework point of view .

ProductDecoratorExtension.cs

namespace DecoratorPattern
{
    public static class ProductDecoratorExtension
    {
        public static void ApplyCurrencyMultiplier(this IEnumerable<Product> products)
        {
            foreach (var p in products)
            {
                p.Price = new CurrencyPriceDecorator(p.Price, .95m);
            }
        }

        public static void ApplyTradeDiscount(this IEnumerable<Product> products)
        {
            foreach (var p in products)
            {
                p.Price = new TradeDiscountPriceDecorator(p.Price);
            }
        }
    }
}

As you can see each of these class are well defined and they are following the SOLID principles with use of Single Responsibility Principle and Open/Close Principle.Now lets build the final piece of the puzzle that is the new and improved ProductService class which will still call the same ProductRepository class to get the list of products and then simple decorate it with the two define decorators and will apply the behavior.

ProductService.cs

namespace DecoratorPattern
{
    public class ProductService
    {
        private IProductRepository _productRepository;

        public ProductService(IProductRepository productRepository)
        {
            _productRepository = productRepository;
        }

        public IEnumerable<Product> GetAll()
        {
            var products = _productRepository.GetAll();

            products.ApplyCurrencyMultiplier(); // Decorate with Currency Multiplier
            products.ApplyTradeDiscount(); // Decorate with Trade Discount
            return products;
        }
    }
}

Lets write a simple unit test to see how we will call the method in the Product Service class.

Unit Test

namespace DecoratorPattern.Test
{
    [TestClass()]
    public class When_testing_product_service
    {
        [TestMethod()]
        public void Should_be_able_to_get_products_using_the_decorators()
        {
            IProductRepository productRepository = new FakeProductRepository();
            ProductService target = new ProductService(productRepository);
            int expected = 2;
            int result = 0;
            IEnumerable<Product> actual = target.GetAll();
            foreach(var p in actual)
            {
                result++;
            }
            Assert.AreEqual(expected,result );
         }
    }
}

I know I am a bit guilty here for not writing a good test, ideally I should assign the base price for all the products as some multiple of 10s and see each of the price being return as some percentage of the value due to the discount and exchange rate but I hope the TDD guys will spare me as it’s more about the decorator pattern.

And now if you look at the final implementation in VS class diagram you will see how close it is to the initial UML diagram in the beginning.

Decorator pattern implementation diagram in VS

Sideline note:-I have been trying to complete this blog for the last three days and learned my lesson that watching comedy movies and writing blog doesn’t play that well 🙂

Strategy Pattern

January 26, 2011 3 comments

In this post I am going to talk about another very common pattern which we all use in our code but aren’t aware of it. In fact once you start thinking and re factoring your code you will see how close some of these patterns and at times confusing as well.

In this context the confusion is that in my previous post about Template Method Pattern I said that when ever you have “switch case” kind of logic then Template Method is a good candidate to be used, but same goes for Strategy Pattern and why not as both come under the “Behavioral Pattern” category.

But there is clear distinction between the two , Template is more of control of flow where as Strategy is pure about decision making or strategies, and don’t worry this confusion will fade away as you start using them more and more in your projects.

Lets start by looking at the UML class diagram of this pattern and then we will dissect it one by one.

Strategy Pattern UML Class Diagram

Nothing complicated and lets see the three main classes of this pattern.

  • Strategy: A class that defines an interface for an algorithm(method)
  • Concrete Strategy: A class which implements the defined interface in the strategy
  • Context: Defines all the strategy and gets the concrete strategy to execute the algorithm.

Phew !! Looks confusing and odd, I mean the class diagram was trying to make some sense and then these three little statements made us throw design patterns out of the window. May be it’s not that complicated as it sounds.

Lets say you are designing a CachePolicy class which at runtime will get some settings from a configuration file and depending on Policy ( Strategy) it will cache the data to the storage. Hmm may be it is starting to make some sense as the policy is our strategy and will do switch from one type of storage to another.

We are also doing pretty good when it comes to Object Oriented Analysis and Design (OOAD) as we have identify a behaviour ( Strategy ) and some Inheritance and polymorphism ( different types of storage but a common behavior ).

Lets look how we would implement if we don’t apply SOLID Principles and design patterns and the code would something like this.

public class CachePolicyService
    {
        public void Store(CachePolicyStrategy cachePolicyStrategy, string key, object data)
        {
            switch (cachePolicyStrategy)
            {
                case CachePolicyStrategy.FileServer:
                    StoreToFileCache(key, data);
                    break;
                case CachePolicyStrategy.WebCache:
                    StoreToWebCache(key, data);
                    break;
                case CachePolicyStrategy.StateServer:
                    StoreToStateServerCache(key, data);
                    break;
                case CachePolicyStrategy.Database:
                    StoreToDatabaseCache(key, data);
                    break;
            }
        }

        private void StoreToDatabaseCache(string key, object data)
        {
            throw new NotImplementedException();
        }

        private void StoreToStateServerCache(string key, object data)
        {
            throw new NotImplementedException();
        }

        private void StoreToWebCache(string key, object data)
        {
            throw new NotImplementedException();
        }

        private void StoreToFileCache(string key, object data)
        {
            throw new NotImplementedException();
        }
    }

Well the code looks okay and lets re factor the code to apply the design pattern and the SOLID principle. As you can see there is a switch statement and this class responsibility is to make the decision but not necessary implement each of its implementation in its private method. Specially if each policy has different storage then the Policy service class has to have knowledge of all these storage types and how to store as well. So i hope you guys are with me that this methods do not belong to the Cache Policy service class (SRP)

Lets follow the SOLID principles and re factor some of the code. First we need to take care of various type of storage and the switching logic, so task in our hand is that the Cache Policy Service need to have a way to store the data but without going into how the data is stored, second the various medium of storing the data is different but have a same algorithm (method) i.e. a common store method ( which means abstract method and polymorphism). This is virtually the strategy pattern in english and lets see this in a class diagram.

Strategy Pattern VS class digram

Wow !! we did a pretty good job and it looks pretty close to the first UML diagram and now we are beginning to see the bigger picture.Lets see the code one by one to understand what it means to implement like that.First we will start with the enum which has various kind of strategy.

Cache Policy Strategy

namespace StrategyPattern
{
    public enum CachePolicyStrategy
    {
        FileServer,
        WebCache,
        StateServer,
        Database
    }
}

Cache Policy

namespace StrategyPattern
{
    public abstract class CachePolicy
    {
        public abstract void Store(string key, object data);
    }
}

File Cache

namespace StrategyPattern
{
    public class FileCachePolicy : CachePolicy
    {
        public override void Store(string key, object data)
        {
           //Store it in the file system
        }
    }
}

and you get the picture for rest of the Cache Policy class, however lets see the main CachePolicyService class and see how we have refactored the “switch” statement to the Strategy Pattern.

Cache Policy Service

public class CachePolicyService
    {
        private readonly Dictionary<CachePolicyStrategy, CachePolicy> policies =
            new Dictionary<CachePolicyStrategy, CachePolicy>();

        public CachePolicyService()
        {
            DefineCachePolicies();
        }

        private void DefineCachePolicies()
        {
            policies.Add(CachePolicyStrategy.FileServer, new FileCachePolicy());
            policies.Add(CachePolicyStrategy.WebCache, new WebCachePolicy());
            policies.Add(CachePolicyStrategy.StateServer, new StateCachePolicy());
            policies.Add(CachePolicyStrategy.Database, new DatabaseCachePolicy());
        }

        public void Store(CachePolicyStrategy cachepolicyStrategy,string key,object data)
        {
            policies[cachepolicyStrategy].Store(key, data);
        }
    }

And this is where we are doing some cool re factoring thing.First we are creating a dictionary of these policies (strategies) and adding the classes which implements the “Store” (algorithm) method, its this way we are creating an array of these objects and when the “Store” method is called in the Service class we access the object by its indices and execute the store method. ( This is what we define as role of the context in the beginning after all it’s not that complicated) 😉

As you can see the method signature is defined on the abstract class and all the Policy classes adhere to it and I think this is biggest strength of OOP. Moreover we applying SOLID principle to this class as now this class knows how to call the store method of each of these policies but is not involved in the underlying logic of how the data is stored.

This is really a very handy and powerful pattern and you will see it’s avenue for implementation is infinite. It can easily be combined with Template Method Pattern or Factory Pattern. It’s main use could be in business objects and business rules for example in Tax or Insurance calculation where various strategy can be applied to calculate the tax/insurance based on various attributes like Person age, gender, salary etc.

Categories: Design Patterns, SOLID Tags: , ,

Template Method Pattern

December 17, 2010 6 comments

In my 16 years of software development I have to say that "Template Method Pattern" is one of the most understated but heavily used pattern, we all have used it in some form or the other but never realized that it is a pattern.In the design pattern world it is define as

  The Template Method patterns defines the skeleton of an algorithm in a   method,deferring some steps to subclasses.

It basically means that the template method will define a series of steps which is a well document process for that domain, however each steps can behave in different ways depending on rules or conditions.Hmmm… sounds very complicated no it’s not.

First lets have a look how the UML class diagram of template method pattern looks

 

Template pattern - UML Diagram

As usual I will start with a simple example and I’ll try my best to be more real world. Lets say you are looking at writing a document processing kind of functionality for an enterprise and this is how the user defines the process..

  Based on different types and the use of the document we have different template,   once the template is applied we just change few names, address etc on the   document, format the document and send it .

Does look like Mail merge sort of stuff and this is how we start working it out in the OOP world.

Document process template 

1) Start up or Initialization.

2) Load meta data.

3) Apply template based on the meta data.

4) Format the document and do some spell check or pagination etc.

5) Finalize the document which could mean send the document.

Wow that’s a lot of methods but that’s what a process in a system would be and you can easily say then when ever you have workflow kind of process with some slight differences of one or two methods then there is a good potential for the template method pattern.

Lets model this in a class diagram with the template method pattern.

 

Document Processor Template model

Hmmm .. so what happened there this looks pretty much what the Template method pattern UML diagram looks and still it’s not that clear. First thing you must be wondering that in the DocumentProcessTemplate all the methods are italics except the Process Document. It simply means that ProcessDocument method is a concrete method and rest of them are abstract and lets write some code for abstract DocumentProcessTemplate class.

Document Process Template

 

public abstract class DocumentProcessTemplate
{
    public DocumentType DocumentTypeTemplate { get; set; }
    public MetaDataType MetaDataTypeTemplate { get; set; }

    public abstract void Startup();
    public abstract void LoadMetadata();
    public abstract void LoadTemplate();
    public abstract void ApplyTemplate();
    public abstract void FormatDocument();
    public abstract void FinalizeDocument();

    public void ProcessDocument(DocumentType documentType,
                                MetaDataType metaDataType)
    {
        DocumentTypeTemplate = documentType;
        MetaDataTypeTemplate = metaDataType;

        Startup();
        LoadMetadata();
        LoadTemplate();
        ApplyTemplate();
        FormatDocument();
        FinalizeDocument();
    }
}

 

Aha so this is what the template method looks like, it is nothing more like a contract.The ProcessDocument method is saying that this is the sequence of steps it takes to process any type of document and the class which implements it can implement it’s own action(methods), but the base class will enforce the sequence of execution.

And lets have a look how these two different time of DocumentProcessor looks like

Letter Processor

public class LetterProcessor : DocumentProcessTemplate
{
    public override void Startup()
    {
        //may be don’t need anything
    }

    public override void LoadMetadata()
    {
        switch (MetaDataTypeTemplate)
        {
            case MetaDataType.Personal:
                // May be we need to do more
                //complex work here..
                break;
            case MetaDataType.Organizational:
                break;
        }
    }

    public override void LoadTemplate()
    {
        switch (DocumentTypeTemplate)
        {
            case DocumentType.Email:
                //Apply email settings
                break;
            case DocumentType.Memo:
                //Apply Memo settings
                break;
        }
    }

    public override void ApplyTemplate()
    {
        // Can be any combination based on meta data return
    }

    public override void FormatDocument()
    {
        //may be we need different formatting
        //based on document type like
        // SpellChecker();
        // Translator(); etc functionality
    }

    public override void FinalizeDocument()
    {
        // Final process which could be
        // for email directly send to
        // the client but for Memo
        // print it out and send an email to
        // the company postal department to
        //dispatch the document.
    }

 
}

Agreement Processor

public class AgreemantProcessor : DocumentProcessTemplate
{
    public override void Startup()
    {
        //Since it’s an agreement may
        //be we need to process some
        // pre requisite documents
    }

    public override void LoadMetadata()
    {
        //Some decision making
    }

    public override void LoadTemplate()
    {
        switch (DocumentTypeTemplate)
        {
            case DocumentType.Letter:
                // some special logic
                break;
            case DocumentType.Memo:
                // some special logic
                break;
        }
    }

    public override void ApplyTemplate()
    {
       
    }

    public override void FormatDocument()
    {
       
    }

    public override void FinalizeDocument()
    {
        //Send to the business review
        //team for a thorough review
    }
}

As you can see how these two document processor class differ in their own implementation. A letter process algorithm based on whether it’s Personal or Organizational will have a different implmentation than a Agreement Processor but it’s the base class which controls(enforces) the execution flow. With this pattern we are still sticking to the good design principles of OOP ( inheritance and polymorphism) and we are also using the Single Responsibility principle, as the single responsibility of the abstract DocumentProcessTemplate is to control the flow of the processing.

This pattern is also useful when there is a lot of cluttering of code with lot of decision making code like if elseif else or two many switch statement or complex calculation(“complex business rules”).

This is just a tip of an iceberg and it’s a very useful,simple yet powerful pattern to use.Rest is upto your imagination and refactoring :).

Adapter Pattern

December 9, 2010 3 comments

In this post I will show you how you can use adapter pattern in your project. First of all the definition of Adapter pattern as wikipedia says is

  In computer programming, the adapter pattern (often referred to as the wrapper   pattern or simply a wrapper) is a design pattern that translates one interface for a   class into a compatible interface. An adapter allows classes to work together that   normally could not because of incompatible interfaces, by providing its interface to   clients while using the original interface.   

It’s some sort of start and I was a bit surprised that in Wikipedia article there was no example in C# ( I know most of the C# programmers were either sleeping or coding when the article was getting written 😉 ).

Anyway it doesn’t matter because a fantastic idea is a fantastic idea it doesn’t matter in which language it is written. It’s quite the same with food and music, if you like it you’ll love it , it doesn’t matter which culture or type it is.

As usual I will start with a simple but a real world example, this is something I have used it myself in a production project and it’s caching. Whether it’s a web or a thick client we all have used some sort of caching mechanism and we typically write something like this in ASP.NET

HttpContext.Current.Cache.Add(cacheKey,
                      value,

                      null,
                      DateTime.Now.AddDays(1),
                      TimeSpan.Zero,
                      CacheItemPriority.Normal,
                      null
);

Well nothing wrong with this is how ASP.NET allows you to put something into the cache and you might be wondering what’s wrong with this. The problem I see with this code is that this code with be sprayed all across my project when ever I want to add something to cache, how do I test this ? Does it adds any value for the enterprise ?? (hmm sounding like an Architect )…well relax we haven’t committed a crime and lets see how we can improve it one step at a time..

So you might say lets start with an interface..good point, let’s do it.

public interface ICacheContext
{
    void Add(string cacheKey, object value);
    object Get(string cacheKey);
}

Ohh..and since we applied the YAGNI principle we almost forgot we need to add the remove method as well so that we can get rid of that item from the HttpCache. So the completed interface looks like ..

public interface ICacheContext
{
    void Add(string cacheKey, object value);
    object Get(string cacheKey);
    void Remove(string cacheKey);
}

Well looks good we can fake a context and easily test, also the class which will implement this interface will have the code and there will be no code smell. If in future Microsoft changes the Cache object to some other object it’s this class which has to change and I don’t have to do find and replace everywhere. So all is good so why am I still bothered ?

Well I don’t like the Context word in it,it looks more like web and as an architect when I am designing this interface I have to think at the enterprise level.

Would this interface will make sense if it is a thick client application or something else?? Isn’t caching is more about a temporary storage ?? And I am taking advantage of some of the cool things which .NET framework provides like instead of object I should use Generics ??

If we look into System.Web.Caching object the object browser you will see how I designed my ICacheContext interface.

System.Web.Cache in Object browser

The Ninja inside you awakes and puts some thoughts into it.

public interface ICacheStorage
{
    void Remove(string key);
    void Store(string key, object data);
    T Retrieve<T>(string key);
}

Ah now it makes sense it looks more real world interface, the interface is more of a conceptual thing with storage and the method names start to make more sense. Moreover this interface (contract) can be used for any kind of application and can be used enterprise wide ( for windows forms, windows service etc)

Now the Adapter pattern comes into act. It’s a very simple pattern and we all use it day in and day out but are not aware that we are using it.

As you saw ICacheContext we created before mimics the method System.Web.Cache object in the Framework. But the new contract we define has different set of methods ( like the different electric current and power point in different countries) and we need a Cache adapter which will adapt to our ICacheStorage interface and expose the Cache object functionality through these interface methods. ( like we have different power adapters for different countries)

Let see how do we describe the adapter pattern in UML class diagram

Adapter pattern UML class Diagram

Makes a lot of sense and the class diagram depicts exactly what we are intending to do.

So now we have to create this adapter which will implement the ICacheStorage interface and when implementing it’s methods it will map the ICacheStorage Remove method to the System.Web.Cache Remove method and so on.

And this is what I have come up with.

public class HttpContextCacheAdapter : ICacheStorage
{
    public void Remove(string key)
    {
        HttpContext.Current.Cache.Remove(key);
    }

    public void Store(string key, object data)
    {
        HttpContext.Current.Cache.Insert(key, data);
    }
    public T Retrieve<T>(string key)
    {
        T itemStored = (T)HttpContext.Current.Cache.Get(key) ?? default(T);
        return itemStored;
    }
}

As you can see this class has a purpose, it implements our ICacheStorage and act as an adapter between the interface and the System.Web.Caching class. It also plays well with SOLID principle as you can see this class will only change if the underlying technology i.e HttpContext/Cache object changes.

By creating the ICacheStorage we have come up with a smart interface and be applied for different Caching strategy.For example you have windows service which uses a file system caching you can simply create a FileCacheStorage object and depending upon above scenario you could decide if an adapter is required or not.

This is my take no how to use the Adapter pattern and it’s a real world example, I hope it can help you refactor your code and encourage you to use it in your code.