Single Responsibility Principle

TohSR
3 min readOct 25, 2020

What is the Single Responsibility Principle?

The Single Responsibility Principle (SRP) is one of the SOLID principles that is used to help developers write more maintainable and extendable software. It was first introduced by Robert C. Martin in his article and he describes it as:

“A class should have one, and only one, reason to change.”

In other words, a class should only have one responsibility. If a class has more than one responsibility, then there will be more than one reason for it to change.

Why should we use the Single Responsibility Principle?

One of the benefits of SRP is that it makes it easier for us to read and understand the code and hence, speeding up the development process. A class that follows the SRP would be more focused and compact, while a class that does too many things may create confusion, making it harder to read and debug.

Using SRP also makes it easier to make code changes and give us fewer reasons to change multiple files. This makes the changes more focused and thus improves encapsulation and cohesion.

Example 1

In the example above, the Rectangle class has two responsibilities:

  • Calculates the area of the Rectangle
  • Drawing the rectangle on the GUI

Rectangle also has low cohesion since geometrics and drawing do not naturally belong together.

Two applications are using the Rectangle class:

  • The ComputationalGeometryApp is a package for geometrical computations, which also uses area()
  • Rectangle provides a method to draw a rectangle. For that, Rectangle uses GUI to implement draw()
  • ComputationalGeometricApp depends on GUI (GUI has to be deployed along with Rectangle) even if it only needs the geometrical functions of rectangles

This violates the SRP as:

  • Rectangle has multiple reasons to change
  • It forces the ComputationalGeometryApp to have a dependency on the GUI class
  • A change in the Rectangle class may lead to a change in the ComputationalGeometryApp and vice-versa
  • Split responsibilities: Rectangle has only one responsibility: draw() & GeometriRectangle has only one responsibility: area()
  • ComputationalGeometryApp uses only GeometriRectangle. It only depends on the geometrical aspects.
  • Both classes can be reused easily and only a change in the responsibilities will affect the class.
  • Both classes are easy to understand: Rectangle represents a rectangle by its visual properties, while GeometriRectangle represents a rectangle shape by its geometric properties.

Conclusion

The main benefits of the Single Responsibility Principle are high-cohesion and low-coupling code. Following the SRP minimizes the chance that one class will have to change for a given requirement, and maximizes the possibility that changing one class will not impact any other classes.

--

--