Do you REALLY know what SOLID means? (#1: Single Responsibility Principle)

Single Responsibility Principle:

Do one thing and do it well!
This principle states that a class should only have one responsibility. Furthermore, it should only have one reason to change. SRP, like most principles out there, can be over-applied. If we create a new class for incrementing integers, then yeah, that may be a single responsibility, but that’s ridiculous! We tend to forget that things like the SOLID principles are there for a purpose. SOLID is a means to an end, not an end in itself. The end is maintainability.

Let’s consider a scenario. We can think of refactoring a class with two methods into two classes of one method each, so as to reduce the number of services injected into its constructor. We can think that this is a simplifying operation, in line with the SRP (single responsibility principle), when all it does is increases the number of classes to manage as well as adding an interface, in the process adding a lot of boilerplate code. More often than not; due to blindly and wrongly following SRP makes our code base more difficult to understand and debug, destroy encapsulation by the need to make everything public in order for the class fragments to be able to communicate; and using dependency injection sometimes made impractical by having to inject so many microscopic services in order to get any work done.

Intuitively, it seems to be wrong that our unit of organisation and encapsulation should be used to encapsulate a single method, or even one or two very short methods. In that case, why even bother with classes, and why not go back to procedural coding? In some specific cases it might be justified but we need to be sure of why we would do this.

The single responsibility principle is a way to help us make our code easier to understand and easier to change. It says that each part of our code should only have one job to do. That way, if we need to change something, we only have to look in one place and we don’t have to worry about breaking anything else.

For example, let’s say we have a class that is responsible for getting data from a database and also for formatting that data into a nice report. According to the single responsibility principle, we should split this class into two separate classes: one for getting the data and one for formatting the report. That way, if we need to change how we get the data, we don’t have to worry about breaking the report formatting. And if we need to change the way the report looks, we don’t have to worry about breaking the data fetching.

In other words, each part of our code should only have one reason to change. That way, our code is easier to understand and easier to maintain.

Reason To Change

We need to pay close attention to the term ‘reason to change’. For example a class for an employee which has methods for calculating and reporting pay, or a class which has data manipulation and data persistence operations; these might be different ‘reason to change’. Also; a reason to change is related to a function in the business which is served by the software: in these cases the classes should be split up because the business function of creating reports and the business function of defining how salaries are calculated are different.

On the face of it, SRP is about where a class has functionality that belongs in two different layers or modules, it should be split. But when people who are following the SRP blindly without understanding the philosophy behind it, they are doing something more general and using it to cut up any class that does ‘more than one thing’.

The idea behind the Single Responsibility Principle is that by limiting the scope of a class or module to a single responsibility, you can make your code more maintainable and easier to understand. When a class or module has only one responsibility, it’s easier to see how it fits into the overall design of your system, and it’s easier to modify or extend the class or module without affecting other parts of the system.

Another apt and proper wording for the SRP is: Gather together the things that change for the same reasons. Separate those things that change for different reasons. It simply means The SRP is about limiting the impact of change.

solid principle
S (single responsibility principle) OLID
Implementing SRP

The trick of implementing SRP in our software is knowing the responsibility of each class. However, every developer has their vision of the class purpose, which makes things tricky. Sometimes only we, as designers of our application, can decide if something is in the scope of a class or not. When writing a class according to the SRP principle, we have to think about the problem domain, business needs, and application architecture. It is very subjective, which makes implementing this principle harder then it seems.

Let’s consider a class that contains code that changes the text in some way. 

public class TextManipulator {
    private String text;

    public TextManipulator(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }

    public void appendText(String newText) {
        text = text.concat(newText);
    }
    
    public String findWordAndReplace(String word, String replacementWord) {
        if (text.contains(word)) {
            text = text.replace(word, replacementWord);
        }
        return text;
    }
    
    public String findWordAndDelete(String word) {
        if (text.contains(word)) {
            text = text.replace(word, "");
        }
        return text;
    }

    public void printText() {
        System.out.println(textManipulator.getText());
    }
}

Here we have two responsibilities: manipulating and printing the text. Having a method that prints out text in this class violate the Single Responsibility Principle. For this purpose, we should create another class, which will only handle printing text.

Delegating Responsibility
public class TextPrinter {
    TextManipulator textManipulator;

    public TextPrinter(TextManipulator textManipulator) {
        this.textManipulator = textManipulator;
    }

    public void printText() {
        System.out.println(textManipulator.getText());
    }

    public void printOutEachWordOfText() {
        System.out.println(Arrays.toString(textManipulator.getText().split(" ")));
    }

    public void printRangeOfCharacters(int startingIndex, int endIndex) {
        System.out.println(textManipulator.getText().substring(startingIndex, endIndex));
    }
}

Now, in this class, we can create methods for as many variations of printing text as we want, because that’s its job. When designing software based on the SRP principle, cohesion is essential, since it helps us to find single responsibilities for our classes. This concept also helps us find classes that have more than one responsibility.
Let’s go back to our TextManipulator class methods:

...

public void appendText(String newText) {
    text = text.concat(newText);
}

public String findWordAndReplace(String word, String replacementWord) {
    if (text.contains(word)) {
        text = text.replace(word, replacementWord);
    }
    return text;
}

public String findWordAndDelete(String word) {
    if (text.contains(word)) {
        text = text.replace(word, "");
    }
    return text;
}

...

Here, we have a clear representation of what this class does: Text manipulation. But, if we don’t think about cohesion and we don’t have a clear definition of what this class’s responsibility is, we could say that writing and updating the text are two different and separate jobs. Lead by this thought, we can conclude than these should be two separate classes: WriteText and UpdateText. In reality, we’d get two classes that are tightly coupled and loosely cohesive, which should almost always be used together. These three methods may perform different operations, but they essentially serve one single purpose: Text manipulation.

Conclusion

The hard thing to remember about the Single Responsibility Principle is that it is based on likely patterns of change, not dependency or functional relationships within the code. Neither the internal structure nor the external function and requirements of the code are key. Rather the nature of the business environment in which the code is undergoing change.

The Single Responsibility Principle (SRP) is a software design principle that states that a class should only have one responsibility, or one reason to change. This can help to make code more maintainable and easier to understand. However, it is important to consider the overall design of the system and the business needs when implementing SRP, as blindly following the principle can sometimes lead to unnecessary complexity and boilerplate code. It is also important to pay attention to the “reason to change” and to separate responsibilities that change for different reasons. The SRP can be implemented by thinking about the problem domain, business needs, and application architecture, and by considering the cohesion of a class and its clear definition of responsibility. It is subjective and requires careful consideration to effectively implement.

The key is not to overthink!

Leave a Comment