Sign in

Single Responsibility Principle

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:

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.

Example 1

  • Drawing the rectangle on the GUI
  • 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
  • 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
  • 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.