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!