Single Responsibility Principle Explained

I propose a better name for this design principle: The Single Requirement Principle.

The Single Responsibility Principle is the most misunderstood design guideline ever, because it has a misleading name.

The name have caused many to believe a class or module should only be responsible for one single thing. This sounds sensible on the face of it, but when you try to apply it more concretely it quickly become impossible to decide what a “single thing” means. Any operation consists of other operations all the way down to the primitives of the language. This thinking leads to code without cohesion, where everything is split into tiny modules. This is not good design.

But the intention behind the principle is quite different. Responsibilities is meant to refers to the requirements and stakeholders behind the software, not the implementation details. It is about what responsibilities the code fulfills for the business or organization.

Consider a classic software development project. Some stakeholders define a set of requirements which the program should fulfill. They do not care how this is implemented in code, as long as the end result fulfill these requirements.

But as we all know requirements change over time. This is the real challenge of software architecture. It is easy to write code which implement a set of fixed requirements. The challenge is to write code which can be changed reasonably easy in the face of changing requirements, without causing unrelated bugs to crop up all over.

The single responsibility principle states that a class should at most be responsible for implementing a single independent requirement. When a requirement change, we should be able to change the relevant code without affecting any other requirement. If the implementation of different requirements is tangled together in the same code, it becomes exceedingly difficult to change one without affecting the other. Therefore, the code should be modular such that responsibilities for independent requirements are also separated in the code.

Of course realistically not every piece of software will have an explicit list of requirements written down. Nevertheless there always are a set of requirements the software must fulfill. The challenge is to figure out which the requirements may change independently.

The bottom line is you can't look at a piece of code in isolation and determine if it conforms to the SRP. You have to look at it at a higher level and take the business requrements and stakeholders into consideration.