Archive

Posts Tagged ‘TDD’

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

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.

EF Code First: Table Per Hierarchy

April 6, 2011 5 comments

Continuing with my previous blog post about Entity framework today I am going to show you how to use Table Per Hierarchy relationship with Code First Approach.

It’s again a very useful mapping scenario and can be used for filtering specific types of domain objects.I am going to use a very simple real life scenario like a Person table and with that we have 2 derived types Players and Coaches, I know this may not be the best example for this kind of scenario but for illustration purpose and keep the example as simple as possible.

Lets first start with a domain model where we want to conceptually map 2 derived entities to a base entity.

Player Coach Class Diagram

and the code for 3 classes are as following :-

public abstract class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateOfBirth { get; set; }
}
public class Player : Person
{
    public int SportId { get; set; }
    public int NoOfGames { get; set; }
}
public class Coach : Person
{
    public DateTime ContractStartDate { get; set; }
    public DateTime ContractEndDate { get; set; }
}

and this is how we define the relationship in the configuration file.

public class PersonConfiguration : EntityTypeConfiguration<Person>
{
    public PersonConfiguration()
    {
        this.Map<Player>(x => x.Requires("PersonType").HasValue("P"))
            .Map<Coach>(x => x.Requires("PersonType").HasValue("C"));
    }
}

and now all we have to do is add the configuration class to the OnModelCreating method of our POCOContext class.

modelBuilder.Configurations.Add(new PersonConfiguration());

Lets write a unit test to make sure the database is getting created and the table are generated with the right column.

[TestMethod()]
public void Should_be_able_to_create_POCOContext_database()
{
    var target = new POCOContext();
    target.Database.Initialize(true);
}

and this is how our People table looks like.

People table structure

So far so good but the best part is the data is flat combined structure in the database but yet in our domain model it is hierarchical and we can treat even the saving or retrieval of data in terms of domain model and not like treating it a data structure and separating the two kinds of Person with just types.

Lets write some more code to see it in action, first we will try adding a new Player into the table.

[TestMethod()]
public void Should_be_able_add_a_player()
{
    var player = new Player
                 {
                    FirstName = "Joe",
                    LastName = "Blogg",
                    SportId = 1,
                    NoOfGames = 120,
                    DateOfBirth = new DateTime(1980, 12, 12)
                 };

    context.Person.Add(player);
    context.SaveChanges();

}

and lets add a coach as well.

[TestMethod()]
public void Should_be_able_add_a_coach()
{
    var coach = new Coach
                {
                    FirstName = "Joe",
                    LastName = "Blogg",
                    DateOfBirth = new DateTime(1960, 1, 2),
                    ContractStartDate = new DateTime(2009, 12, 1),
                    ContractEndDate = new DateTime(2012,12,1)
                };
    context.Person.Add(coach);
    context.SaveChanges();
}

As you can see it can’t be easier than this and the power of this feature is then you are retrieving records of either a player or a coach type.

[TestMethod()]
public void Should_be_able_to_get_Players()
{
    var players = from p in context.Person.OfType<Player>()
                select p;

    var result = players.ToList();
    Assert.AreEqual(1,result.Count);
}

By just using OfType on the Person Entity the EF is doing the filtering of records based on the type and it’s doing all hard work. Hope you guys find it quite handy and use it in your project.

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

Loosely Coupled Architecture

December 1, 2010 4 comments

In this post I will give you another interesting perspective into designing loosely coupled architecture. Lets first see what does Wikipedia says about Loose Coupling ..

  In computing and systems design a loosely coupled system is one where each of its   components has, or makes use of, little or no knowledge of the definitions of other   separate components.  

In some of previous post I showed how dependencies between components/services can be decoupled by interface (contract) and it is the contract each component cares about.It does not care how it is implemented and who has implemented it. Then we introduce IoC/Dependency Injection which determines which component will be used when any part of the system calls that interface. To decouple we simply have the interface passed to the constructor of the class and this is called constructor injection and same way you can have method injection as well.

As usual I will start with a basic example and see how we go from there.So for example you are writing a batch job or some piece of code which execute some Update to the database using an Id. (I know this sounds quite vague but very soon you’ll see what I am getting into).

So let’s see how it appears to our mind :-

public interface IDbTask
{
    void Execute(int id);
}

As a good architect you should always anticipate change.The code works fine but in future I am anticipating that the criteria will become more complex and I have to factor that in because the business is evolving.

Let’s say the criteria is id plus something more like if the date is Tuesday and the first name is like this or that ..blah blah ..you got the picture. Keeping this in mind I would create the interface contract as this ..

public interface IDbTask
{
    void Execute(IActionParameter param);
}

and for the first iteration this is how my interface IActionParameter looks like.

public interface IActionParameter
{
    int id { get; set; }
}

see at this point I am just defining the contract no actual implementation. So now the BA comes and says we need to add the date parameter and since we are doing real Agile we have to adhere to the open close principle i.e. we should not change the IDbTask nor the IActionParameter

But with the open close principle this class or interface can be extended ( remember extensibility). So we will go ahead and extend it.

public interface IDateActionParameter : IActionParameter
{
    DateTime Date { get; set; }
}

and just for the sake of it and to see the bigger picture a class implementing the interface would look like

public class DateActionParameter : IDateActionParameter
{
    public int id { get; set; }

    public DateTime Date { get; set; }
}

Now since DateActionParameter still implements the base interface i.e. IActionParameter we can still pass it as is and we didn’t change the signature of the execute method.

I know you might be thinking that we still have to change inside the code to factor the 2 parameters in your decision-making. Well may be or may be not ;-) . I mean if you really want it like that,then there are much complex and sophisticated patterns to implement and this is the first baby step.

The fundamental thing is there has not been any brut force signature change and you are not breaking anything. You are extending it, hopefully you will also see how IoC/DI plays a big part on designing such components.

Lets see this in another more real life scenario like the repository layer, business layer, web service layer etc.Suppose you are implementing a simple Customer business layer and for easy illustration I am just going to show CUD i.e. Create, Update, Delete( and Read will come later)

public interface ICustomerBL
{
    void Update(ICustomer entity);
    void Add(ICustomer entity);
    void Delete(ICustomerActionParameter param);
}
 

As you can see it’s pretty simple all the interface and it’s actual implementation like Customer and CustomerActionParameter will be injected by IoC/DI and we are keeping everything clean.

There is no tight coupling and it has full extensibility , anything can be chop and change on the fly and still everything works.

If I have to test the Add method with a  fake object all I have to is implement the ICustomer interface and create it’s fake implementation.

So you might be thinking if everything is so cool and easy then why am i holding onto the Read and if you haven’t figured it out then here is the big deal with it ..(drum roll)… the problem lies in its method signature ..

public interface ICustomerBL
{
    void Update(ICustomer entity);
    void Add(ICustomer entity);
    void Delete(ICustomerActionParameter parameter);
    ICustomerDO Get(IActionParameter parameter);
    List<ICustomerDO> GetAll(ICustomerActionParameter parameter);
}

At surface it all looks okay and the ICustomerDO is supposed to be a domain object which might have a different properties or behaviour as compare to your database entity “customer” (it’s always a good design pattern to not expose your database entity directly to business layer,service layer or UI layer).

Now the real problem lies how do I new up this object with out hard coding it ?

You might say Oh ! that’s easy like in the previous post we will just use the constructor injection …hmmm good thinking but isn’t our constructor already preoccupied by this :-

public class CustomerBLICustomerBL
{
    private readonly ICustomerRepository _repository;

    public CustomerBL(ICustomerRepository repository)
    {
        _repository = repository;
    }

    public void Update(ICustomer entity)
    {
        _repository.Update(entity);
        // just for illustration
        // same for add and delete
    }

    public void Add(ICustomer entity)
    {
        _repository.Add(entity);
    }

    public void Delete(ICustomerActionParameter parameters)
    {
        _repository.Delete(parameters);
    }

    public ICustomerDO Get(IActionParameter parameter)
    {
       
    }

    public List<ICustomerDO> GetAll(ICustomerActionParameter parameter)
    {
        //Call to the Repository and it return a list of
        //Customers from database but we need to map the
        // database customer to the Customer Domain
        //Object and hence we need to new up an object
    }
}

and you might also say well change the signature of Get and GetAll so that it takes the required interface and through our IoC/DI container we will inject the actual class. And you might implement it something like this

public ICustomerDO Get(IActionParameter parameter,ICustomerDO customerDO)
{
    //perform some logic of extraction
    // and mapping and then return the object
    return customerDO;
}

 


public List<ICustomerDO> GetAll(ICustomerActionParameter parameter,List<ICustomerDO> listCustomer)
{
    //Call to the Repository and it return a list of
    //Customers from database but we need to map the
    // database customer to the Customer Domain
    //Object and hence we need to new up an object
    return listCustomer;
}

Yes this approach will work but if we need to extend this we will have to change the method signature and what if it needs more than just 2 interfaces or the depending objects have their own dependencies on other objects.(Like Logging using ILogger interface etc).

It will be ugly to pass all the interface through methods and I rather not do that. So how do i solve this problem ?

This is where the factory pattern which I mentioned in my this post comes handy.

To implment this factory and the DI I am going to use the AppServiceFactory provided by David Hayden and the code of AppServiceFactory looks like this.

public sealed class AppServiceFactory
{
    private static readonly AppServiceFactory _instance = new AppServiceFactory();
    private IWindsorContainer _container;

    public static AppServiceFactory Instance
    {
        get { return _instance; }
    }

    public T Create<T>()
    {
        return (T)_container.Resolve<T>();
    }

    private AppServiceFactory()
    {
        ConfigureServiceContainer();
    }

    private void ConfigureServiceContainer()
    {
        _container = new WindsorContainer();
        _container.Register(
            AllTypes.FromThisAssembly().BasedOn<IWindsorInstaller>()
            );
        ServiceLocator.SetLocatorProvider(() =>
           new WindsorServiceLocator(_container));
        var installers =
            ServiceLocator.Current.GetAllInstances<IWindsorInstaller>();

        foreach (var installer in installers)
        {
            installer.Install(_container, null);
        }

    }
}

I have taken his pattern as is and improvise a little bit.I first tell IoC container(Castle Windsor) to look for all classes which implement the interface IWindsorInstaller and register all the installers with the windsor container then set Service Locator to current container and get all the instances of these classes.By the virtue of the fact that these classes implement the IWindsorInstaller interface (contract) I know they have the install method and I iterate through this installers and execute the install method.

And now I can use it just like the way I would use the normal windsor container i.e.


     ICustomerDO  customerDO = AppServiceFactory.Instance.Create<ICustomerDO>();

 

If you are finding some of this stuff quite different it;s perfectly alright.May be you haven’t come across these scenarios or may be you have,and you might have a different way of solving the problem.The important thing is that we are working for the same goal i.e. Loosely coupled architecture and not newing objects directly and there is always different ways to skin a cat important thing is the effort.

In my opinion in todays day and age you should not be hard-coding classes and should not new up objects directly,it’s the IoC/DI job and let it handle it (SRP).

Service locator pattern with Windsor Castle

November 22, 2010 7 comments

I have done a couple of post on SOLID and interface driven design and I hope it gives you some insight into designing the architecture, and how you leverage good design principles and architecture to develop a loosely coupled systems.

For me it’s the architecture which is more important than the actual technology. As you can see some of my examples are in ASP.NET MVC, but it can be applied to any technology.

You can’t just use SOAP, web XML RPC and call it a loosely coupled architecture. It’s the interface design( the contract ), the separation of concern and SOLID principles which gives a  remarkable design.

One of the key thing to which I give a lot of emphasis is Inversion of Control/ Dependency Injection principle. Like other principles it is a very simple one and it’s not limited to ASP.NET MVC. If you are doing any workflow development, SOA services, enterprise level web services, integration project, middleware anything consider using this principle as well. As your system grows you will see it benefits.

If you want to know what a service locator pattern is then please refer to architecture and patterns guru Martin Fowler here. The idea is to have one registry of object and it’s dependencies and the service locator will find these services and register with the Ioc container.

One more important things is that when i talk about services it has nothing to do with SOA and web services. Consider it as a component which implements an interface and does the job. This is more of an architecture debate and I leave it up to you guys to decide what to call what, important thing is loosely coupled architecture and components.

So in order to use service locator with castle windsor you have to download it from the codeplex website. The service locator is also available for others IoC/DI like SPRING.NET, Unity, StructureMap , Autofac etc and you can get it from codeplex. Add the WindsorServiceLocator.cs file to your project.

 

Add reference to castle.core.dll and casle.windsor.dll in your project, if you’re new to Castle windsor please refer to my previous article “Getting started with Castle Windosr” in order to get up and running with it.

Now we will start thinking . . .

As we know that Castle Windsor has an interface call IWindsorInstaller and it has got just one method contract i.e Install. Which is quite fantastic as we are already seeing some SOLID principle i.e. Interface Segregation and Single Responsibility :)

Lets make use of this interface and create some installers. I prefer it this way as you are compartmentalized how your components(services) will get register with your IoC container

 

public class PersonInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Component.For<IPerson>().ImplementedBy<Person>()
            );

    }
}

and a couple more for a better illustration.

public class LoanApprovalServiceInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Component.For<ILoanApprovalService>()
                     .ImplementedBy<LoanApprovalService>()
            );

    }
}

 

public class CreditHistoryCheckInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Component.For<ICreditHistoryCheck>()
                    .ImplementedBy<CreditHistoryCheck>()
            );

    }
}

 

This is just an example and I am sure in a real life production system each of these units(installers) will have many components registering.

Now what we are going to do is register these installers with our IoC container and ask service locator to search for these installers and execute the install method in each installer .

 

IWindsorContainer container = new WindsorContainer();
var servicelocator = new WindsorServiceLocator(container);
container.Register(
    Component.For<IWindsorInstaller>()
             .ImplementedBy<PersonInstaller>(),

    Component.For<IWindsorInstaller>()
             .ImplementedBy<CreditHistoryCheckInstaller>(),

    Component.For<IWindsorInstaller>()
             .ImplementedBy<LoanApprovalServiceInstaller>()
    );

ServiceLocator.SetLocatorProvider(() =>
                        new WindsorServiceLocator(container));

var installers =
    ServiceLocator.Current.GetAllInstances<IWindsorInstaller>();

foreach (var installer in installers)
{
    installer.Install(container,null);
}

 

In the code you will not see much advantage as it is quick prototype but imagine when your system is big and you have 100+ or 500+ interfaces and services.This is where you are thinking like an architect and thinking, how much the system will grow? how you will cope up with the changes ? and what different blocks and component you can chop and change without affecting other parts of the system ?

Suppose for above example in PersonInstaller along with Person I have a PersonRule component which implements a business rule (behaviour)and that rule changes you simply change the PersonRule component by implementing the interface and creating a new class.It’s dependencies on other components will not change as all other components use the interface and not a hard-coded class. It’s your IoC container which will decide which component will get created and not the calling code. (again single responsibility principle)

Hope this will give you some insight into the architecture and design of your current and future projects and feel free to get in touch with me, I still have so many interesting and mind boggling scenarios and ideas.

Interface & TDD Part -2: The Factory pattern

November 12, 2010 5 comments

If you guys remember back in June I did a post on interface and TDD. A very simple example in which we applied SOLID principle and separation of concern to re factor our code. I think it is more like re-factoring in our thinking, when we talk about agile we have to think like one.

If you haven’t read it yet please read it here and give me your feedback. I like the comments and came across this comment by Mr. Monk…

Monk :

So in this way how would you prevent that the fake classes get compiled for a release version?

Comment

I quickly replied to the good fella but realize will it make sense, is this really going to make things clear to him . It’s not making sense to me so how would it make sense to him. So I thought I better post it, as the crux of this matter is not in the code but in the thought process i.e. agile thinking. So lets tackle this and see what’s the problem is …

As you can see in the fake test and in the real test we are newing up the object and although it solves our purpose but it is not a good design.

  1. We have hard code the class and we have tight coupling.
  2. We are sort of breaking the single responsible principle as the invoking code (consuming code) is creating the object and using it too.

So lets see how can we can decouple the dependency and create a class which does the job of creating the right object so that we can make sure that all the test when run will invoked the fake drive method and when we run this in production then the real drive code gets executed.

And the answers to this is …(drum roll) …Factory Pattern. I know it’s a very old pattern we all have knows but never really seen in practice or makes sense…aha so we have heard that’s 50% job done as Factory means creating something and we have a problem here of creating something ;-) . Lets start with a simple abstract class and we will call it BaseDriveFactory

public abstract class BaseDriveFactory
{
    public abstract IDrive CreateDrive();
}

As you can see we are creating an abstract class which creates an object of type IDrive ( Deep slow breath we are moving into the zone )…

 

Then we create 2 Factory classes for Fake and Real Drive Object …

public class FakeDriveFactory : BaseDriveFactory
{
    public override IDrive CreateDrive()
    {
        return new FakeDrive();
    }
}

and

public class RealDriveFactory : BaseDriveFactory
{
    public override IDrive CreateDrive()
    {
        return new RealDrive();
    }
}

Now you might be thinking hmm..may be I can write an if else logic to decide which object to call and depending on some flag, int or enum I will do the switch and return the right object. Well in theory it is alright but we haven’t thought agile enough and some single responsibility principles so we do some more thinking .

Now the factory are in place and we are ready to go and do the magic ..hmm may be we need a generator class which will do the creation ..good point lets do it ..

public class DriveFactoryGenerator
{
    private readonly IDrive fakeDrive;
    private readonly IDrive realDrive;

    public DriveFactoryGenerator(BaseDriveFactory factory)
    {
        fakeDrive = factory.CreateDrive();
        realDrive = factory.CreateDrive();
    }

    public void Drive(IDriveFactorySettings settings)
    {
        if (settings.ObjectFactory == "default")
        {
            realDrive.Drive();
        }
        else
        {
            fakeDrive.Drive();
        }
    }
}

Sounds interesting and looks good we have done re-factoring quite well and separation of concerns is also well implemented. If you notice I have also introduce and interface called IDriveFactorySettings. Now you must be saying what the heck why we need it, well agile thinking means anticipation and I will do a post very soon on that too but for the time being lets see what it looks like

 

public interface IDriveFactorySettings
{
    string ObjectFactory {get;set;}
}

As you can see with that interface I am just creating a contract(interface) and saying that any class which wants to manage this has to implement the interface and we are in business. I am not hardcoding it to say that it has to be from a config file or xml or registry. This is the beauty of separation of concerns and interface design is that we don’t care about the implementation.

So in order to override the behaviour all I have to do is change the IDriveFactorySettings and we get what we want. As far as the problem Mr. Monk has had all I have to do is implement a BaseTest class which all my UnitTest will inherit and have the objectfactory as anything other than “default”

So i would do something like this

public class FakeDriveFactorySettings : IDriveFactorySettings
{
    public string ObjectFactory
    {
        get { return "Fake"; }
        set { ObjectFactory = value; }
    }
}

 

and the base test class will look like

 

public class BaseTest
{
    private readonly IDriveFactorySettings _settings;
    private readonly DriveFactoryGenerator factoryGenerator;
    private readonly BaseDriveFactory factory;
    public BaseTest()
    {
        _settings = new FakeDriveFactorySettings();
        factory = new FakeDriveFactory();
        factoryGenerator = new DriveFactoryGenerator(factory);
    }

    public virtual void TestDrive()
    {
        factoryGenerator.Drive(_settings);
    }
}

and the test would look like

[TestClass]
public class DriveTest : BaseTest
{
    public override void TestDrive()
    {
        base.TestDrive(); // calling the fake one
                          //as it already set for
                          //the entire test
                         
    }
}

The final class diagram..
Class Diagram

that’s it from me and guys keep your comments coming.I would like to know your perspective into the whole SOLID way of thinking and as well interesting problems you guys face in your daily coding :)

Automapper

November 2, 2010 3 comments

Recently a friend of mine was talking to me about his interesting project and in the conversation I mentioned him to use Automapper. As he was not aware of it but when I started explaining him he really got intrigued by it. I provided him the link and thought about blogging about it.

As you have guess it, it’s mainly a very smart mapping tool and will do all your left right hand code mapping. Whether it’s a MVC project where you do a lot of mapping between View-Model to DTO’s or whether you are working in an integration, this is something you can’t miss. You can download the assembly from codeplex at http://automapper.codeplex.com/releases/view/44802

Lets see some examples. Lets say i have two classes PersonDisplayVm & PersonDto and the dto instance is called item and the Vm instance is called model. So inorder to map the two objects so that we can copy value from dto to model we create a map between the classes and use the Map function to map it like this.

  Mapper.CreateMap<PersonDto, PersonDisplayVm>();
  Mapper.Map(item, model);

and this is how my two classes look like

public class PersonDisplayVm
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int? Age { get; set; }
    public DateTime CreatedDateTime { get; set; }
}

public class PersonDto : IPersonDto
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int? Age { get; set; }
    public DateTime CreatedDateTime { get; set; }
}

As you can see it already saved a lot of lines of code where we have to painstakingly assigning  value of one attribute in the left hand side to the corresponding value in the right hand side.

Following TDD and our good habit of writing test lets write a quick test.

[TestFixture]
public class When_testing_person_mapping
{
public PersonDto GetPersonDto()
{
     return new PersonDto
                {
                    Id = 1,
                    FirstName = "Joe",
                    LastName = "Blogg",
                    Age = 45,
                    CreatedDateTime = DateTime.Now
                };
}

[Test]
public void Should_be_able_to_map_dto_to_vm()
{
     var dto = GetPersonDto();
     var vm = new PersonDisplayVm();
     Mapper.CreateMap<PersonDto, PersonDisplayVm>();
     Mapper.Map(dto, vm);
     Assert.IsTrue(dto.Id == vm.Id);
}

Now lets say if for some reason in my display view-model I have the created datetime as string if we try to do a automapping from view-model to dto then we get an exception like

Exception of type ‘AutoMapper.AutoMapperMappingException’ was thrown.

as the string datetime when intialize with DateTime.Now add AM PM string into the string field and automapper can’t map it directly.In order to fix this problem you have to create a custom type convertor like this

public class DateTimeTypeConverter : ITypeConverter<string, DateTime>
{
    public DateTime Convert(ResolutionContext context)
    {
        return System.Convert.ToDateTime(context.SourceValue);
    }
}

And add the custom type converter before our mapping happens like this

[Test]
public void Should_be_able_to_map_dto_to_vm()
{
    var dto = GetPersonDto();
    var vm = new PersonDisplayVm();
    Mapper.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter());
    Mapper.CreateMap<PersonDto, PersonDisplayVm>();
    Mapper.Map(dto, vm);
    Assert.IsTrue(dto.Id == vm.Id);
}

And you will see our test this time passes with no exceptions.

Now lets say you have another system or some legacy code where the Person class returned has a PersonId field instead of Id and it would be real waste to write another class which looks like the legacy class and write the whole mapping yourself.

This is where some of extensibility point of this mapper comes into play so lets say your legacy class or any other class looks like this.

public class PersonLegacyDto
{
    public int PersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int? Age { get; set; }
    public DateTime CreatedDateTime { get; set; }
}

to map the PersonId field to Id field in PersonDto class you can simple specify it like this.

[Test]
public void Should_be_able_to_map_legacy_to_dto()
{
    var dto = GetPersonDto();
    var personLegacy = GetLegacyPerson();
    Mapper.CreateMap<PersonLegacyDto, PersonDto>()
        .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.PersonId))
        ;

    Mapper.Map(personLegacy, dto);
}

and you will see it does rest of the stuff, the .ForMember is an fluent interface so you can chain them for multiple property mapping.I use it quite often as it saves tones of writing left hand right hand code and saves a lot of time and energy. Hope you will find it handy to use and although I am using it in MVC project but can be used in any service/data layer project as well.

Follow

Get every new post delivered to your Inbox.