Tuesday, 30 July 2013

O is for the Open/Closed Principle (Strategy pattern) - Part One

Introduction

The Open/Closed principle is concerned with the modification of code.

Open for extension, but closed for modification

The idea is that when we need to make a code change, we don't want to modify existing modules, but to write a new module instead. This keeps our modules separated and potentially reusable for other areas of code.
To achieve this, Robert C. Martin suggests two patterns:
  • Strategy pattern
  • Template method
In this blog, I will be covering the Strategy pattern. I will cover the Template method in part two.

Strategy pattern

The key to this pattern is the use of an interface. It allows us to create an abstraction between two concrete classes and reduces the coupling between them.

To demonstrate this pattern, I will use an example of an electrician that is capable of only holding one tool at a time (Toolboxes aren't invented yet) which they use to fix electrical problems.

The Problem

Below is an example of NOT using the strategy pattern:

 class Program
    {
        static void Main(string[] args)
        {
            Spanner spanner = new Spanner();
            Electrician electrician = new Electrician(spanner);

            electrician.OperateTool();

            Console.ReadKey();

        }
    }

Here we have a program that creates an Electrician object that accepts a Spanner in the constructor.
We then call the OperateTool method which will print text to the console indicating that the Electrician has successfully used the Spanner.

So far, so good.  The electricity is back on and running!

However, in another program, the Electrician needs to use a ScrewDriver for a job. But the Electrician only knows how to hold a Spanner. (I guess due to a lack of training?)

In order to support this requirement, we will have to change the Electrician class so that it can provide a constructor overload for supporting a ScrewDriver class. See below:

 class Electrician
    {
        private Spanner spanner;
        private Screwdriver screwDriver;

        public Electrician(Spanner spanner) {
            this.spanner = spanner;
        }

        public Electrician(Screwdriver screwDriver) {
            this.screwDriver = screwDriver;
        }

        public void OperateSpanner()
        {
            spanner.Operate();
        }

        public void OperateScrewdriver()
        {
            screwDriver.Operate();
        }
    }

A few problems with this:
  1. We needed to modify the Electrician class.
  2. This solution doesn't support the potential for other tools being needed. What if the electrician needs a hammer?!!
The solution? We fire their arse and get someone who is capable of holding all kinds of tools! Actually, that's slightly unfair - we should train them instead!

The Solution - The Strategy Pattern

We want a solution that gives us an Electrician class which is capable of supporting any potential tool. To do this, we use an interface which all tools will implement. The Electrician class will then use the interface. This will then support any tool class that successfully implements the interface and therefore will be easily pluggable to the Electrician class.

Below shows the program creating two Electrician objects that support different tools:

    class Program
    {
        static void Main(string[] args)
        {
            ITool spanner = new Spanner();
            ITool screwDriver = new Screwdriver();

            IWorkman bob = new Electrician(spanner);
            IWorkman dick = new Electrician(screwDriver);

            bob.OperateTool();
            dick.OperateTool();

            Console.ReadKey();
        }
    }

As you can see the Electrician object can now support multiple tools in a single constructor.

Below shows the new Electrician class:


    class Electrician : IWorkman
    {
        private ITool tool;

        public Electrician(ITool tool) {
            this.tool = tool;
        }

        public void OperateTool()
        {
            tool.Operate();
        }
    }

The Electrician class now operates against the ITool interface which means that only one field and one method is needed to be capable of supporting all types of tools.

Below shows the ITool interface and the two tools that implement it:


 interface ITool
    {
        void Operate();
    }



 class Spanner : ITool
    {
        public void Operate()
        {
            Console.WriteLine("The spanner has been used.");
        }
    }


 
 



 class Screwdriver : ITool
    {
        public void Operate()
        {
            Console.WriteLine("The screwdriver has been used.");
        }
    }

The magic here is that if another tool is ever needed in future. We won't need to modify the Electrician class to support this new tool. Instead we can have the tool implement the ITool interface, so it can be injected into the Electrician class.

Conclusion

The Strategy pattern removes the dependency between classes by providing a layer of abstraction.
This allows the code to conform to the Open/Closed principle. It removes the need to modify classes which may potentially break the code, instead we can extend the code by creating new classes that implement an interface.

As a result, we now have code that is modularised and safer to implement changes. It allows classes such as the Electrician class to be reusable by having it support any class that implement the ITool interface.

Robert C. Martin suggests that a project shouldn't overuse abstraction as it is only needed in areas that are likely to experience frequent change. This makes sense because creating an interface for every class that is unlikely to change may take up a lot of production time. So only use it when it makes sense.

In part 2 we will look at the Template method and how that can also be used to help aid us with conforming to the Open/Closed principle.


 


No comments:

Post a Comment