Patterns, Principles, SOLID

SOLID – Open Closed Principle (OCP)

As stated previously… I am getting (or trying to get) back to basics.

It is my belief that developers have to often times refactor the way they think and the way they approach things from time to time to make sure that the basics and principles are still strong.

So let’s take a look at one of the principles in SOLID; Open Closed Principle (OCP)

OCP simply states:

Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification

In my mind following this principle is not limited to inheriting from a base class and marking methods and properties as virtual. While I do believe that there is a time and a place for following OCP in this manner I feel that this is sometimes the only solution that developers think of when thinking about OCP.

Take the following example of following OCP through inheritance.

public class OrderService {
  private readonly IRepository<Order> repo;

  public OrderService(IRepository<Order> repo) {
    this.repo = repo;
  }

  public virtual void Save(Order order) {
    repo.Save(order);
  }
}

public class EmailOrderService : OrderService {
  private readonly ISmptService emailService;

  public EmailOrderService(IRepository<Order> repo, ISmptService emailService)
    : base(repo) {
    this.emailService = emailService;
  }

  public override void Save(Order order) {
    base.Save(order);
    emailService.SendNotification(order);
  }
}

Ok so now we have these classes and we are clearly following OCP but I believe that there is an alternative through use of the Strategy pattern which would make this a little cleaner.

public class OrderService {
    private readonly IRepository<Order> repo;

    public OrderService(IRepository<Order> repo) {
        this.repo = repo;
    }

    public void Save(Order order) {
        repo.Save(order);
    }

    public void Save(Order order, IOrderStrategy strategy) {
        this.Save(order);
        strategy.Process(order);
    }
}

public class EmailOrderStrategy : IOrderStrategy {
    private readonly ISmptService emailService;

    public EmailOrderStrategy(ISmptService emailService) {
        this.emailService = emailService;
    }

    public void Process (Order order) {
        emailService.SendNotification(order);
    }
}

Here we can see that OCP is still being followed since the OrderService class is still open for extension via the IOrderStrategy and is closed for modification. We don’t need to mark any methods as virtual and don’t need to inherit from the OrderService class. What is even better is that we could have implemented a Specification pattern along with the Strategy pattern and really get cooking.

public class OrderService {
    ...
    public void Save(Order order, IEnumerable<IOrderStrategy> strategies) {
        this.Save(order);
        foreach (var strategy in strategies) {
            if (strategy.CanProcess(order))
                strategy.Process(order);
        }
    }
}

public class EmailOrderStrategy : IOrderStrategy {
    ...
    public bool CanProcess(Order order) {
        return order.SendEmail;
    }
    ...
}

So I guess all this really means is that OCP shouldn’t only be thought of as marking methods and properties as virtual. OCP should be thought about and reasoned about a little more deeply and carefully.

And granted the examples given here have holes and are more than likely not the best code you have ever seen but it is the ideas these examples show that should be taken.

Advertisements
Standard
.Net, Patterns

Dependency Injection – Why should we care?

In my previous post we covered (briefly) Inversion of Control (IoC) and Dependency Injection. In this post we will discuss why we should use Dependency Injection and how it can improve our every day coding life.

Again… from my previous post we found that we can inject objects and values a particular class is dependant upon through the constructor or through property setters. But this really begs the question of why you would want to do that? Well there are a couple of benefits from doing this:

  1. Identifying dependencies for a particular class becomes easier
  2. Inheritance fully describes dependencies
  3. Dependencies become easier to test, mock or stub

So lets take each of these reasons one by one and give some brief examples. Consider the following class as an example:

Sample Code

As we can see from this simple example the "EmployeeRate" class is dependent upon the "Employee" class. Not only that but we can also see that in order to get the "Employee" class we need to make a call to the database to retrieve the information.

Let’s suppose that someone else is trying to create an instance of this class. Another developer would never know that this class uses the "Employee" class and it might very well be that they are already working an "Employee" class. So if instead we refactor this class to follow the Dependency Injection pattern, anybody would be able to quickly tell that the "Employee" class is indeed a dependent class.

 Refactored Employee Rate Class 

(If you are like me you more than likely wouldn’t stop there. After looking further into the code you might have seen that there is no real need to have a constructor for this class at all. Instead, simply make the two methods static and pass the "Employee" class in as a parameter. For the purpose of this post however… let’s just play along)

Let’s now take a look at how the inheritance model would benefit from using the Dependency Injection pattern.

Let’s once again take the original example and create a new class called "ManagerRate." This class needs to do some things that a normal employee wouldn’t have to do like factor in the number of employees they manage. Regardless of the reason, we need to calculate a managers rate differently then an employee. We could add a "switch" statement or "if … else" condition to apply this logic but… being good little developers we created this class.

Manager Rate Class

Here we can see that it is not clear to the "ManagerRate" class what dependencies the base class requires. Not only that but if we put our "extensibility" hat on for a second we can see that if an employee and a manager are ever broken up to be separate classes then we would have a problem and would more than likely result in a change in logic in both classes. Let’s now see what our "ManagerRate" class would like from our refactored version.

Refactored Manager Rate Class

Now the "ManagerRate" class can clearly see what the dependencies are for the base class. And if we put our "extensibility" hat back on we could see that we might still have an issue if an employee and a manager are separated into two classes but the code change would only need to occur in one class and more than likely it would only require they type to change. If we really wanted to do it up correctly we would create an interface for the "Employee" class.

Finally, let’s look at how testing can benefit from our use of the Dependency Injection pattern.

If we go back to the original example and look at what happened in the constructor we would see that the constructor called a static method on the "Employee" class named "GetById." Suppose now that we want to test the "EmployeeRate" class to ensure that it’s "CalculateSpecialRate" method returned the correct value. How would we go about doing that?

First we would need to make sure that we have a database with valid (or good) data in it for a given "Employee." Normally we would insert a new row in the corresponding table and record the resulting primary key or "id." Then when we ran our unit test we would need to make sure that we pass in the correct "id" to our "EmployeeRate" constructor.

If, however, our data gets deleted, modified, or someone else is running our unit tests in another environment then our tests would fail. It wouldn’t fail because our code is wrong but because the supporting data is missing. So what are we really testing in this scenario… the code or the data?

If we follow the Dependency Injection pattern as we did in our refactored code then we would be able to create reliable and "database proof" unit tests. By passing in a mock or stub of an "Employee" class, the data being used will always be the same and our unit tests will always be testing the code and not the data.

Another benefit that we did not have time to cover is how Dependency Injection is used in Aspect Oriented Programming (AOP). There are plenty of other posts out there that cover AOP that I recommend you read. In short… being able to intercept calls and inject other objects, values, or classes based on the cross-cutting concerns is not only the point behind AOP but dramatically reduces code and increases code reuse.

In this post we covered three out of many benefits to using Dependency Injection. Hopefully the examples drive this point home and starts to make you rethink the way you design and write code in your everyday life.

Standard
.Net, Patterns

Inversion of Control and Dependency Injection

MVC has not only brought about a change in how we think about designing and building web applications on the .Net framework but it has also reminded most of us about the Inversion of Control (IoC) and Dependency Injection patterns. While most of us have used these patterns before (without even knowing about it), I think that it is very important to understand what these patterns are, how to use them, and why they are important not only with MVC but in everyday "coding" life.

IoC and DI are defined and described at length in an article written back in 2004 by Martin Fowler named "Inversion of Control Containers and the Dependency Injection pattern" that I highly recommend everyone read. I am not going to go into great details about these patterns but…

  • IoC means that an object gets other objects that it relies on through an outside source or framework
  • Dependency Injection means that an object gets other objects that it relies on through it’s constructor or set properties

It is safe to say that these are the same but just remember that there is a difference. I have also found that when people or articles have talked about IoC they have been really talking about Dependency Injection. So enough about that… what does it look like?

Let’s start with a simple class which relies on a Data Access class (named "MyDataAccess") to connect to some database…

MyObject class 

Imagine now that the "MyDataAccess" implements an interface named "IDataAccess" and we change the code to reflect that…

Sample MyObject 

But now if our example changes one more time… and this time we add yet another class which implements the "IDataAccess" interface, we would have to add more logic or code to determine which concrete class should be created…

Sample MyObject 

Clearly this is going to be a problem each time we want add a new class which implements the "IDataAccess" interface. Now expand this out to several classes which depend upon an "IDataAccess" object and you start to see the overhead with maintaining that code.

Enter the Dependency Injection pattern where we pass in an "IDataAccess" object as a parameter to the constructor. This then moves the responsibility (or control) of creating the "IDataAccess" object outside of our class or outside of it’s scope.

MyObject class 

So now any time someone creates an instance of this class they can clearly see that it needs or depends upon an "IDataAccess" object. We have also increased the test-ability of our class by being able to pass in stubs or "mock" objects.

In my next post I will cover more of the benefits and show it works amd how it is used in Testing, MVC and LINQ frameworks.

kick it on DotNetKicks.com

Standard