Thursday, 1 August 2013

O is for the Open/Closed Principle (Template method) - Part Two

Introduction

Behold! Part two of the Open/Closed principle blog and it's going to be a cracker!

Here, I will be covering the template method and how it aids our code with conforming to the Open/Closed principle. These methods and principles are based on Robert C. Martins book - Agile principles, Patterns and Practices in C#.

Part one covered the strategy pattern, I recommend reading it before proceeding.
"It's brilliant!" - me.


Recap

Let's recap slightly on the Open/Closed principle. Remember Robert's all important motto?

Open to extension but closed for modification

We have no interest in modifying code in previously created modules. Instead, we would like to create a new module to contain our new logic.

Template Method

Ok, so how can the template method help us?

The template method essentially uses inheritance to separate code workflow from implementation.
But as always, there is no better way to explain this but with an example.

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

            var bob = new Electrician(screwDriver);
            var billy = new Electrician(spanner);

            bob.OperateTool();
            billy.OperateTool();

            Console.ReadKey();
        }
    }

Similar to what we saw in part one - we have two Tool objects being created and an Operate method being invoked on each of them. This will simply print out text stating that the tool has been used. Do you suspect that Screwdriver and Spanner may possibly be subclasses of Tool? hmm...

Below shows our abstract class Tool:

  abstract class Tool
    {
        public abstract bool IsToolReady();
        public abstract void OperateTool();

        public void Operate() {
            if (IsToolReady()) {
                OperateTool();
            }
        }
    }

The Tool class is indeed a parent class which defines an Operate method and two abstract methods. The Operate method is our Template method! This means that the code within defines a logical flow or a code template. It is for the subclasses to provide the code for these methods.

The logical flow in this case is that we want to ensure the tool is ready to be used before using it because the last thing we would want to happen is our power drill exploding.. right?

The Operate method calls our abstract methods which (as you may have noticed) doesn't have any implementation yet. So what do we do?!

Well luckily, these methods are abstract and will need be implemented by a subclass which inherits from our Tool class. For example:

    class Spanner : Tool
    {
        public override bool IsToolReady()
        {
            Console.WriteLine("Spanner has been adjusted and is now ready to be used.");
            return true;
        }

        public override void OperateTool()
        {
            Console.WriteLine("Spanner has been used.");
        }
    }

Sorry, I know it's not doing anything impressive. But we do however have our implementation for the two abstract methods IsToolReady and OperateTool!

This is essentially the magic to the Template method. The parent defines a predetermined logical flow that calls abstract methods which are implemented in the subclasses. Not much to it!

The logical flow should be true to all subclasses of the parent, otherwise it is not a true child. This logical flow should never have to be altered.

Advantages

The advantages this brings are as follows:
  1. The Electrician only needs to be aware of the Operate method. This is good abstraction and keeps the Electrician naïve to inner workings of the tool.
  2. We can now create any tool that inherits from Tool and this can be used in our Electrician without changing any of its code.
  3. We have a logical workflow which will be enforced on all subclasses. This means that we only need to be concerned with writing code for the abstract methods.


Conclusion

Our code now conforms to the Open/Closed principle. If we needed a new tool such as a PowerDrill 
then we wouldn't have to be worried about changing the Electrician logic to support it.

The Electrician class is able to support any class that inherits from Tool. This is most ideal if we suspect that it is likely that the tool logic is likely to change. For example, more types of tools are expected to be used by the electrician.

However, subclasses being only concerned with writing implementation for abstract methods means that the programmer may not be aware of how these methods are used. Bare this in mind when using this principle.

So, we have finally created a successful a design that means that any new tools will be an extension to the code and will cause minimum modification to any existing code. The ultimate advantage being that we are less likely to break code when adding new functionality. Well done.

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.


 


Wednesday, 8 May 2013

S is for Single-Responsibility Principle (SRP)


Introduction

This will be the first of a series of blogs covering the SOLID principles which were created by the legend that is Robert C. Martin.

The SOLID principles concern the design of object-oriented programming in initial design and in code maintenance. These five principles are the golden checklist that a developer should become finely tuned with if they wish to write super maintainable code.

I strongly recommend reading this book, if you wish to dive more into these principles:

'Agile, Principles, Patterns and Practices in C#' by Robert C. Martin

You can get it here:
http://www.amazon.co.uk/Principles-Patterns-Practices-Robert-Martin/dp/0131857258
(This link may not actually be the best price - so do your shopping!)

My goal of these blogs is to take what I have learnt from this book - summarize the principles whilst applying my own examples and thoughts. I intend for these blogs to be short and concise and any feedback would be greatly appreciated.

These blogs might be useful to you if you are:
  • New to OOP and never heard of the SOLID principles before.
  • Needing a quick reminder of these principles.

Single-Responsibility Principle (SRP)

This is by far one of the simpler principles to understand but can turn out to be one of the hardest to implement. This principle mainly concerns the design of classes.

Each class should represent a single responsibility and concept. The reason for this is so that classes are:
  • Easy to understand
  • Changes can be made without breaking functionality.
For example, below show's an interface for a class:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
namespace Solid
{
    public interface IPlayer
    {
        void Shoot();
        void Reload();
        void AddToInventory();
        void RemoveFromInventory();
        void Walk();
        void DriveCar();
    }
}

This interface provides a contract for a player to a game.

The good OO developers among you will quickly notice that this interface is bad.. very bad.

First of all - imagine what the implementation to this class would look like. I can imagine plenty of fields and many, many lines of code. This means the code will be unreadable and will therefore be hard to maintain.

Secondly, it is not clear what this class represents. You might suspect that it represents some sort of walking bag that is brandishing a semi automatic, that is also capable of driving a Ford Mustang.

Well, let me tell you it isn't. Well, it could be.. it is an interface after all.

But in the context of the class itself, it is doing too much for it to be clearly defined as just a player.

I can identify at least three areas of responsibility here:
  1. Gun
  2. Inventory
  3. Transport
Below show's my recommendation for three new interfaces:

1
2
3
4
5
6
7
8
namespace Solid
{
    interface IGun
    {
        void Shoot();
        void Reload();
    }
}

1
2
3
4
5
6
7
8
namespace Solid
{
    interface IInventory
    {
        void Add();
        void Remove();
    }
}

1
2
3
4
5
6
7
namespace Solid
{
    interface ITransport
    {
        void Travel();
    }
}

There is no reason why the Person class should contain the implementation for how a gun shoots and reloads. The person's relationship with a gun should be abstract. This means the classes are shorter and easier to understand. I bet Clint Eastwood didn't need to be concerned with gunpowder, springs and triggers when shooting a dozen villains. He just needed to pull the damn trigger!

By creating these separate areas of responsibility, it means that the functionality between these classes is not coupled. It will be harder to break code in other areas of responsibility if a change needs to occur. Also, if I need to change how the Inventory works, it mean's that I don't have to recompile Transport and Gun.

A little extra

You may have noticed that I have introduced ITransport with a Travel method, and that I have removed any mention of DriveCar and Walk.

My reason for doing this is that I felt walking and driving a car is a method of transport and so I reached out for the abstraction. What this means is that I can now create two classes that implement this interface called Walking and Car that both have the Travel method, but provide their own implementations for travelling.

This becomes extremely powerful when Dependency Injection is involved which means I inject implementation into an object. More of this in later blogs!

But only if change is imminent!

SRP suggests that you should only split a class into separate responsibilities if these classes are likely to change.

One of the main reasons for splitting a class is the risk of the coupled two responsibilities. If in the future, you make a change that you think affects one of the responsibilities, it may actually break the other responsibility without you realising.

If a class has been badly designed to have two responsibilities, but it is unlikely to ever change; then there may actually be no point in changing it.

Conclusion

The main point here is that a class should represent one thing - a single responsibility. There is no limit to your abstraction but there can be a risk of over doing it and making classes too segregated when they don't need to be. So do what makes sense and don't get too carried away.

In the book, it points out that you should only split classes up if they are likely to change in the future. I am in two minds over this as I would be tempted to split the classes for the sake of readability. Also, although classes may seem unlikely to change, there is no way of being certain of the future.

However, if you are working under a deadline and there is a lot of risk with changing a class when it is probable that it won't change - then perhaps there is reason to leave it alone.


Monday, 6 May 2013

Benchmarking Different Data Structures - Part Two (List vs Queue vs LinkedList)


Introduction

This is part two of the benchmarking article. In this article, I will use the BenchHelper class library I made in part one to benchmark the performance of various data structures and draw a conclusion.

The reason why I wish to conduct this experiment is because in most projects I use a list due to my familiarity with it and it's ease of use. However, from what I have read, a list may not be ideal for all scenarios. So by  becoming more familiar with other data structures and knowing their performance implications; I can make reliable decisions in which to use in the future.

For these tests, I wish to create benchmarks for adding a number of items to the end of a collection and also for removing from the beginning of a collection. Consider this as a FIFO experiment between different methods.

The results and conclusions in this article should not be taken as defining reasons for picking a data structure over another, as there are many different reasons that will influence your decision. These tests compare simple adding and removal scenarios, but there are other (more efficient ways) to use these data structures.

These experiments were run on a machine with the following spec:
  • Intel Pentium Dual-Core T2310 1.46GHz
  • 2GB memory
  • Windows 7 Professional

Data Structures

Below is an overview of the data structures I will use for this experiment:

List
A list is a non-fixed sized collection. It provides methods for adding, inserting and removing items in the collection with an index. An internal array is used which doubles in size once the size of the array has been reached. I use this collection data type more than any other due to it's ease of use.

Queue
A queue is a first-in first-out (FIFO) collection data structure. This means that the first item you store in the queue will be the first item that is retrieved from the queue. Queue provides no methods for accessing items via an index. A stack implements LIFO which is opposite to the queue.

Linked List
A doubly linked list is a data structure that contains a node which stores a value and a reference to the next and previous node. This provides a memory advantage because the references to a node are only known when a node that references it is accessed.

Methods

Below shows my main method for this program. This is explained in part one.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
 private static void DoMultiRunTests()
        {
            var numberOfTestRuns = 100;
            var loopTest = new LoopTest(sizeOfCollection);
            var test = new BenchmarkTest(loopTest);

            PrintTest(String.Format("**Average of adding {0} items to a LinkedList. Test has been executed {1} times**", sizeOfCollection, numberOfTestRuns),
                test.DoTest(AddToLinkedList, numberOfTestRuns, ClearLinkedList));
            PrintTest(String.Format("**Average of adding {0} items to a List. Test has been executed {1} times**", sizeOfCollection,numberOfTestRuns),
                test.DoTest(AddToList, numberOfTestRuns, ClearList));
            PrintTest(String.Format("**Average of adding {0} items to a Queue. Test has been executed {1} times**", sizeOfCollection,numberOfTestRuns), 
                test.DoTest(AddToQueue, numberOfTestRuns, ClearQueue));

            PrintTest(String.Format("**Average of removing {0} items from a LinkedList. Test has been executed {1} times**", sizeOfCollection, numberOfTestRuns),
                test.DoTest(RemoveFromLinkedList, numberOfTestRuns, ResetLinkedList));
            PrintTest(String.Format("**Average of removing {0} items from a List. Test has been executed {1} times**", sizeOfCollection, numberOfTestRuns),
                test.DoTest(RemoveFromList, numberOfTestRuns, ResetList));
            PrintTest(String.Format("**Average of removing {0} items from a Queue. Test has been executed {1} times**", sizeOfCollection,numberOfTestRuns),
                test.DoTest(RemoveFromQueue, numberOfTestRuns, ResetQueue));
        }

Below shows the collection methods I have used for populating and removing from a collection. I pass these methods as an Action to the BenchmarkHelper.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
        private static void AddToList(int i)
        {
            list.Add(i);
        }

        private static void AddToQueue(int i)
        {
            queue.Enqueue(i);
        }

        private static void AddToLinkedList(int i)
        {
            linkedList.AddLast(i);
        }

        private static void RemoveFromList(int i)
        {
            list.Remove(i);
        }

        private static void RemoveFromQueue()
        {
            queue.Dequeue();
        }

        private static void RemoveFromLinkedList()
        {
            linkedList.RemoveFirst();
        }

Results

Below shows a table of the results in milliseconds:

                                           Number of items added to the queue
Method 1000 5000 10000 15000 20000
list.Add 0.02993 0.155719 0.351502 0.423189 0.559053
queue.Enqueue 0.03525 0.387643 0.314305 0.460395 0.614273
linkedlist.AddLast 0.12743 0.558551 1.171819 2.131805 2.454959

                                           Number of items removed from the queue
Method 1000 5000 10000 15000 20000
list.Remove 0.821567 13.926008 53.429491 128.310909 224.46324
queue.Dequeue 0.031785 0.149658 0.3079 0.436147 0.580466
linkedlist.RemoveFirst 0.047381 0.231816 0.47043 0.71891 0.882717

Graphs

Below shows a graph visually comparing the speeds:
This graph shows that the amount of time to add items to a linked list increases rapidly after 5000 items, whereas the queue and list maintain a slight incline. In fact, the amount of time it takes to add items to a queue and list at 20000 items takes a similar amount of time to adding items to a linked list at 5000 items.

Possible reasons for this is that a linked list creates a new memory allocation for each added item, whereas a list uses an internal array which exists under a single memory block - this suggests that the time it takes to create a new node reference takes longer than accessing and recreating an internal array. Also, as the list grows bigger, the number of times a list needs to recreate the array will decrease because the capacity will double in size meaning it needs more items to exceed the limit.

From what I have read in the past, a linked list only provides a performance advantage when you need to access a location in the middle of the collection. However, in the case of adding an item to the end of a collection - a linked list is not satisfactory and I would prefer to use a queue or list.


This graph shows a very large performance difference between the list.Remove implementation and the other remove methods. There is only a slight difference between these methods at the 5000 item mark, but beyond this the list.Remove method performance drops considerably.

I appreciate this may not be the ideal approach to remove from a list as there are alternative methods such as RemoveAll but I haven't yet experimented with this (perhaps you can). However, this experiment clearly shows that using list.Remove for removing 5000+ items is definitely not the approach to use.



This graph is a closeup of the previous graph but for comparing the queue and linkedlist. Both of these methods perform well and are steady and reliable. The only conclusion I can make is that a linkedList is slightly faster.

Conclusion

The purpose of this experiment was to test two specific scenarios - adding to the end of a collection and removing from the start of a collection (FIFO). 

The adding to a collection experiment had clearly shown that when adding over 5000 items to a collection, the linkedList.AddLast method should not be used. It had taken 2.45 ms to add 20000 items whereas the queue had taken 0.6 ms and the list had taken 0.5 ms. You are likely to not notice the difference in the running of the application, but if are to add a larger number of items to a linked list then the performance affect may become more noticeable.

The removing from a collection experiment has revealed that the list.Remove method is super unreliable and should not be used with a collection size of more than 5000 items. I have read that the RemoveAll method is a much faster solution and would possibly more complete in this scenario - so use that instead!

It appears that for this particular experiment; the queue is the best overall performer here - which isn't a surprise seeing as it is specifically a FIFO implementation. The list.Remove had poorly performed in removing large amounts of data and the linkedlist.AddLast had under performed in adding large amount of data.

Wednesday, 1 May 2013

Benchmarking Different Data Structures - Part One (Building the Library)

Introduction

Comparing the performance of data types is a practice all developers should conduct if you are building performance intensive software. By doing so it will help guide you in choosing the best data type to use and will also give you a more in-depth understanding of various data types. These tests are known as benchmarking.

Recently I wanted to learn about the performance of certain data structures to help me with future development.

This article is split into two parts. The purpose of this part is to share a benchmarking class library that I created to assist me with this investigation. The second part will show my results and conclusions of my testing of these data structures.

Test Environment

I wanted a test environment that is able to populate and remove from a collection with a large amount of data. The environment must be able to run a test a specified number of times, so that an average can be calculated producing a trusted set of results.

I have created a class library called BenchmarkHelper.

Usage

Below shows the main method of my test program that uses the BenchmarkHelper:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
 private static void DoMultiRunTests()
        {
            var numberOfTestRuns = 100;
            var loopTest = new LoopTest(sizeOfCollection);
            var test = new BenchmarkTest(loopTest);

            PrintTest(String.Format("**Average of LinkedList tests executed {0} times**", numberOfTestRuns),
                test.DoTest(AddToLinkedList, numberOfTestRuns, ClearLinkedList));
            PrintTest(String.Format("**Average of List tests executed {0} times**",numberOfTestRuns),
                test.DoTest(AddToList, numberOfTestRuns, ClearList));
            PrintTest(String.Format("**Average of to Queue tests executed {0} times**",numberOfTestRuns), 
                test.DoTest(AddToQueue, numberOfTestRuns, ClearQueue));

            PrintTest(String.Format("**Average of removing from LinkedList executed {0} times**", numberOfTestRuns),
                test.DoTest(RemoveFromLinkedList, numberOfTestRuns, ResetLinkedList));
            PrintTest(String.Format("**Average of removing from List executed {0} times**", numberOfTestRuns),
                test.DoTest(RemoveFromList, numberOfTestRuns, ResetList));
            PrintTest(String.Format("**Average of removing from Queue executed {0} times**", numberOfTestRuns),
                test.DoTest(RemoveFromQueue, numberOfTestRuns, ResetQueue));
        }

The DoMultiRunTests method creates an instance of a LoopTest and uses it to create a BenchMarkTest instance. The LoopTest implements the interface ITestType which can be used for creating alternative performance tests.

The BenchmarkTest class has a method called DoTest which accepts three arguments:

 public double DoTest(Action method, int numberOfRuns, Action resetMethod)
  1. The method you wish to test.
  2. The number of times you wish to run this method.
  3. The method to clear the state of a test in between each test run.
(Action is a delegate that allows you to inject methods into another method)

DoTest returns a double which will be an average in milliseconds of all the test runs.

BenchmarkTest.DoTest

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
    public class BenchmarkTest
    {
        private ITestType testType;

        public BenchmarkTest(ITestType testType)
        {
            this.testType = testType;
        }

        public double DoTest(Action method, int numberOfRuns, Action resetMethod)
        {
            var timeSpan = new TimeSpan[numberOfRuns];
            method();

            for (int i = 0; i < numberOfRuns; i++)
            {
                resetMethod();
                timeSpan[i] = testType.CallVoidMethod(method);
            }

            return timeSpan.Average(x => x.TotalMilliseconds);
        }

The purpose of this method is to run a test type a number of times and returning an average of how long they all took to execute.

It begins by invoking the test method without recording the time it takes.This is due to Just-in-time compiling which means the method initially taking longer upon it's first call and thus making our average unreliable.

During the loop, I invoke a reset method. This is to provide the opportunity to put the state of any data types back into an initial state. For example, repopulating a Queue so that we can test the dequeue functionality.

You may now be asking what does testType.CallVoidMethod do?

ITestType.CallVoidMethod

Below shows the interface ITestType:

1
2
3
4
5
    public interface ITestType
    {
        TimeSpan CallVoidMethod(Action method);
        TimeSpan CallArgumentMethod(Action<int> method);
    }

An implementation of this represents a type of performance test. The implementation that I wished to use for my testing is a simple for loop and so I created a class called LoopTest:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
    public class LoopTest : ITestType
    {
        private Stopwatch stopWatch = new Stopwatch();
        private int size;

        public LoopTest(int size)
        {
            this.size = size;
        }

        public TimeSpan CallVoidMethod(Action method)
        {
            stopWatch.Reset();

            stopWatch.Start();
            for (int i = 0; i < size; i++)
            {
                method();
            }
            stopWatch.Stop();
            return stopWatch.Elapsed;
        }

This class's responsibility is to run a method a number of times and to return how long it had taken using Diagnostics.Stopwatch.

Conclusion

The BenchmarkHelper is reusable as you are able to pass in methods to test using the Action delegates and you can also implement ITestType to create your own type of performance tests. This means that this handy little assembly can be used in all my projects where I wish to do benchmarking.

Also, do a Bing search on profiling for testing the performance of your code. Tools such as SlimTune Profiler   attach to your assemblies and are able to show you where there might be performance issues in your code. I may possibly do a blog in the future about profiling but there is plenty of information out there already for you.

See part two for putting this library to use!

Tuesday, 16 April 2013

TDD - The art of writing maintainable code

I was introduced to Test Driven Development (TDD) just over a year ago and I only wish I was introduced to it sooner. Like many other developers switching over to TDD, I had to undergo a complete shift in my thinking and approach to development -  it wasn't easy.

I am a programmer and believe it or not, nothing satisfies me more than jumping straight into the code and hacking away. But I found that as the code base grew, it became easier to break logic / features in other parts of the application. I believe this can send a developer into a spiral of paranoia, not wanting to dive into code and be bold in refactoring. This is not healthy and can quickly bring about unmanageable code.

We need something we can trust, something to give us reassurance - to be that child in the code playground, knowing that our parents are watching over us, making sure we don't hurt ourselves or set fire to the swing.

Good points

TDD allows us to keep our modules safe from the unexpected. If I modify a methods implementation then I want to be sure that the function still produces the same expected output when I inject certain arguments.

TDD also allows you to write awesome modularised code!

If you are writing unit-tests then ideally you should using TDD anyway. This means that you write your tests first so that you consider the design of your code.

For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
 [TestMethod]
        public void RomanNumeral_8_Test()
        {
            // Arrange
            var expectedResult = "VIII";
            var number = 8;
            var converter = new NumberConverter();

            // Act
            var result = converter.ConvertToRomanNumeral(number);

            // Assert
            Assert.AreEqual(expectedResult, result);
        }


I take this as far as instantiating objects and invoking methods in my unit tests before I have even created these classes. BECAUSE THAT'S JUST HOW I ROLL! Then using a few shortcuts I can create implementation in moments. This allows me to think of code in abstract modules; I can design my program in classes and methods and spend time coming up with good names.

A few days later, I realise that I could have implemented the roman numeral conversion using a dictionary instead of writing multiple conditions. TDD gives me the safety net to carry out this change without worrying about whether I have broken a module. The change is shown below:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 public class NumberConverter
    {
        private Dictionary<int,string> romanMap = new Dictionary<int, string>();

        public NumberConverter()
        {
            romanMap.Add(1,"I");
            romanMap.Add(2, "II");
            romanMap.Add(3, "III");
            romanMap.Add(4, "IV");
            romanMap.Add(5, "V");
            romanMap.Add(6, "VI");
            romanMap.Add(7, "VII");
            romanMap.Add(8, "VIII");
            romanMap.Add(9, "IX");
        }

        public string ConvertToRomanNumeral(int number)
        {
            if (number >= 10 || number <= 0) return "";
            return romanMap[number];
        }
    }


If however you jump straight into the code (not thinking too much about modularisation) and write a set of classes which contain methods that have 30+ lines of code, then I am quite certain you will find difficulty in creating tests for this code. You will probably end up refactoring a few classes, breaking logic elsewhere and causing some serious trouble. Long story short - ALWAYS write your unit tests first.

Now that you have a completed set of unit tests for a dozen classes, You can be confident. You can dive into the code, refactor like a madman (or woman) and then run the unit tests to see if you have broken anything.

Bad(ish) points

However, TDD is not perfect and it does have it's problems. For example, you have written a large number of tests because you are a TDD boss and you have a large code base. However, for some reason you now need to undergo a large refactor. You do so and run the tests - 30 tests are now failing. Fixing these tests may take as long as the refactoring job itself and as a result it has doubled the amount of production time in producing this change.

Some see this as bad, however, I see it as a small price to pay for writing SUPER-MAINTAINABLE code! Plus, if you didn't have these tests, you probably would have decided against the refactor job in the first place.

Another problem with writing unit tests (if not done properly) is that you have a large set of tests that can take up to 5+ minutes to execute. This is bad. Tests should execute almost instantly. You will probably find yourself having to run these tests very often, probably every time you commit your code into source control.

Don't let your unit tests damage your productivity!

Overall

TDD is great! It enables you to consider the design of your code first, your code becomes very modularised as it needs to be in order to be testable and it ensures you don't break stuff.

However, TDD can eat into your productivity and slow you down. But I don't personally see this as a bad thing as we are writing super maintainable code that will ultimately save us time in the long run.

To sum up:

Good:

  • Keeps modules safe from unexpected changes.
  • Write modularised code.
  • Design your code first.

Bad:

  • Large refactor jobs may mean time spent fixing lots of tests.
  • If tests take long to run, it may slow you down.

Saturday, 13 April 2013

Minesweeper - Using recursion to reveal a region of mine-free squares

A few weekends ago, I thought I would tackle an infamous code dojo problem - the dreaded minesweeper.

We all know it. The idea is simple, we reveal a grid whilst avoiding the mines that lay hidden beneath.

The reason why I decided to blog about this is because it's not every day that I find a scenario to use recursion, but it is however well suited for this problem.

Recursion is when a method calls itself and is used for solving many computational problems, especially in games. In this article, I am technically not having a method call itself, but a form of recursion is happening.

Please note: When I mention a square, cell or coordinate, just consider them as a square on the grid. Knowing the exact difference here is not required to appreciate what I am doing with recursion :) 

Problem

A common problem which may cause a sweat or two (or none) for a developer is the revealing of the mine-free squares.

This occurs when you select a square which reveals a region of mine-free squares until it reaches a square that is connected to a mine. This is what the green squares are in the image below:


(Actual in-game footage!!)

I built this game using C#, WPF with Net Framework 4.

Solution

I decided to use the magic that is recursion for solving this problem.

The method below is what is invoked when a square has been clicked. The implementation then goes through a process of invoking 'RevealNextCell' for each surrounding square.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
 internal void Reveal(int x, int y)
        {
            RevealNextCell(x - 1, y - 1);
            RevealNextCell(x - 1, y);
            RevealNextCell(x - 1, y + 1);
            RevealNextCell(x + 1, y);

            RevealNextCell(x, y - 1);
            RevealNextCell(x, y + 1);
            RevealNextCell(x + 1, y - 1);
            RevealNextCell(x + 1, y + 1);
        }

The 'RevealNextCell'  begins by fetching the coordinate (square) and checking that it is a valid cell to be processed and if it isn't we return on the method - When using recursion it is important to not forget your return conditions or you may get into trouble.

'IsBlank' checks the mine counter on the coordinate (The counter is set when the mine field is first created) to determine whether it is a mine-free square or not. If so, it sets the colour of the cell (Yes, this shouldn't be hard coded!) and finally invokes 'Reveal' which will got through the process of checking all the surrounding squares of this cell.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
        private void RevealNextCell(int x, int y)
        {
            var coordinate = GetCoordinate(x, y, mappedCoordinates);
            if (coordinate == null) return;
            if (coordinate.State == State.Revealed) return;

            if (IsBlank(coordinate))
            {
                coordinate.State = State.Revealed;
                coordinates[x, y].Cell.Background = Brushes.LightGreen;
                Reveal(x, y);
            }
            else
            { 
                coordinate.State = State.Revealed;
                coordinates[x, y].Cell.Child = new TextBlock() { Text = coordinate.Counter.ToString() };
                coordinates[x, y].Cell.Background = Brushes.Goldenrod;
            }

        }


To conclude, recursion is a great technique for solving many game problems and can save you from writing nasty nested loops which are unreadable. Recursion can however be dangerous and you may end up writing infinite recursion - just be sure to write that return condition!

Also, you may be at risk of stack overflow if you use deep recursion so be cautious when using it but in the case of a simple 20 x 20 minesweeper grid; it works like a charm and it keeps your code clean and easy to read.

Happy mining!