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();
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!
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
In the upcoming posts, I will be covering the rest of the principles in the SOLID principles. Till then happy coding!!