In modern day world just knowing how to write code is not enough. If you have ever played chess, you would know that the way grand masters play their game is totally different from the way novice or even intermediate players play. It has been proven scientifically that grand masters are always playing for patterns in a game of chess. When a beginner is faced in a position he just starts thinking of all the possible moves that he can make, but a grandmaster sees the overall position of the board and knows where the game is heading. He knows what is the best solution already for that position and therefore for him the options are very limited as he is just focusing on the patterns that he has learned over the years.

Computer programming is no way similar to chess, we are faced with new challenges and problems everyday and these problems are ever so more complex then a games of 64 squares. One thing that we have in common though is different design principles and patterns that have been established over the years by professional developers to help us in writing better quality code. SOLID Principles are five design principles where each letter in the word SOLID stands for one design principle. SOLID principles are perhaps the most talked about and most frequently used design principles in computer programming world and mastering them can certainly improve the way you code a lot.

In this article I will try to cover the “S” of SOLID principles which stands for the “Single Responsibility Principle”.

What is Single Responsibility Principle (SRP)

The SRP states that:

Every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility.

In simple words SRP simply says that a class should only one do one thing and do it really well. If a class only does one thing than it means that it has only one reason to change. Making your classes follow this one simple principle allows you to have loosely coupled design that is easier to maintain and modify.

Consider the following scenario. We have a class which needs to print a report. In order to print the report it needs to get the report data. We also want the ability to print the report on various sized papers so our code needs to have the ability to print reports on paper size A4, Legal, Letter etc. The developer that wrote code might write code like this


public class Report
{
    public void Process()
    {
        var data = GetData();
        SetReportFormat("A4");
        PrintReport(data);
    }
}

Now in first look, this looks like a very clean code but ask yourself the question, is this class only doing one thing? The answer is no. This class is responsible for fetching the report data, formatting the report and for printing it. In the future if we need to make changes to any of those responsibilities then we will need to alter this class. Thus it is violating the SRP.

In order to fix this problem, we will refactor the code and break it into three separate classes the ReportDataRetriever class, the ReportFormatter class and the ReportPrinter class.

After refactoring, our code will become

public class Report
    {
        private readonly ReportPrinter _ReportPrinter = new ReportPrinter();
        private readonly ReportFormatter _ReportFormatter = new ReportFormatter();
        private readonly ReportDataRetriever _ReportDataRetriever = new ReportDataRetriever();

        public void Process()
        {
            var data = _ReportDataRetriever.GetData();
            _ReportFormatter.SetReportFormat("A4");
            _ReportPrinter.PrintReport(data);
        }
    }

We have ended up having three separate classes each of them with its own distinct responsibility. In the future if we need to make any changes to the way we retrieve the data, we will only need to make changes to the ReportDataRetriever class. Simply by refactoring our code into separate classes we have decoupled our code and made it much more easy to extend and modify in the future!

A common mistake that beginners make when they first read about the SRP is to break their code into very tiny classes that are not highly cohesive and think that they have achieved SRP. A class that has only one method is not much different than code written in procedural languages. It is very important to understand that it is not just enough to break your code into smaller classes but it is equally important that your classes should be highly cohesive.

An easy way to identify whether your class is cohesive or not is by checking whether the methods in the class are utilizing most of the variables and properties (State) of the class. If your methods are only using some the state variables and properties, then it might be a code smell that your class is performing multiple operations and you should maybe consider refactoring it into multiple classes.

In modern days there are very powerful tools at our disposal such as Resharper and Code Rush that allow us to refactor our code by just pressing a few key strokes. Personally when I am coding, I just like to complete my task first and then refactor my code in the same sitting later. It’s just my own style as I feel that if you are worrying about all these principles you tend to focus less on the real task at your hand, but once I do complete my task, I always refactor my code for better design!

Summary

The SRP is one of the most important rule that allows us to write clean, loosely coupled code that is easy to maintain and extend. When we write code we want it be just like making a pasta, where each ingredient is made separately and has its own unique taste and aroma. You can just mix them together and make pasta as per your own liking Smile

In the upcoming posts, I will be covering the rest of the principles in the SOLID principles. Till then happy coding!! Smile