Single Responsibility Principle

Let’s start our journey on SOLID principles by describing the Single Responsibility Principle (SRP).

SRP states that each class should have one responsibility only and, therefore, only one reason to change. It means that every class should have one job to do or one single purpose. Of course, we still allow adding multiple methods/properties and members as long they relate to that single responsibility.

Applying SRP will change your existing code and the first impact will be at the class level: the classes in your projects will become smaller and cleaner. As a note, you shouldn’t be worried about changing the classes even you will notice the increased number of new classes. All major programming languages allows you to organize classes using namespaces and project folders. Keeping your code into classes tightly focused into a single purpose leads to code that is simpler to understand and maintain.

Having small and cohesive classes reduces the code fragility by decreasing the chance of a class to contain bugs (reducing the need for changes). As the classes will perform only one duty, multiple classes will work together to achieve larger tasks. It allows you to easy modify the features, either by extending existing classes or introducing interchangeable versions.

Along with the other principles, SRP allows you to achieve loose coupling.

srpSource: Solid motivational pictures

Example:

Let’s consider below code snippet that violates the SRP principle and then refactor it to comply with the principle.

The above class will read gold price from an independent trusted “source” and check if the price is under certain threshold and it will decide to alert me if I need to buy some gold.

There are at least few reasons to change the above class. Let’s consider at some point I need to add a new “trusted” independent source for gold price. Perhaps I want to change the way I’m evaluating the opportunity to buy gold. Or I would like a more sophisticated system to be notified instead of logging out to console.

To refactor the code, we’ll separate the functionality into three classes. The first is GoldMeter.cs that will retain GoldPrice property and ReadGoldPrice method as both are close related. The other methods are removed so that the only reason to change is the replacement of the “trusted” source price.

The second class is GoldPriceChecker.cs that will include a very simple method to compare the price with a certain acceptable value. The only reason to change the class is if the acceptable value is changed.

The final class GoldPriceAlert.cs will display the alert if a very simple way. GoldMeter class is dependency injected. The only reason to change the GoldPriceAlert class is if we decide to enhance the alert system.

The refactored code below breaks some SOLID principles just to ensure the SRP is visible. Further refactoring of the code is required to achieve SOLID compliance.