Archive
Why program against an interface ?
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.
- Interface design promotes better unit testing and TDD
- Building loosely coupled architecture
- Decorator Pattern
- Dependency Injection ( Getting Started with Castle Windsor )
- Specification Pattern
- Extension by Composition
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.

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.


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.

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.
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
)