2025 Public Training Schedule
January 14 – 17, 2025 – Agile Analysis and Design Patterns – Half-Day Sessions
(c) 2024 To Be Agile
The Single Responsibility Principle says that any entity, whether a class, a method, or a module, should have a single responsibility.
But what is a “responsibility” and how big is it? Is a feature a responsibility or a task or what? I like how Bob Martin defines a responsibility. He says any entity such as a class should have one reason to exist and therefore one reason to change. So a responsibility is *a reason to change*, and this can get very small indeed.
The Single Responsibility Principle echoes the code quality cohesion. Cohesive classes are about one thing. Cohesive methods are about fulfilling a functional aspect of that one thing. While I see developers violate the Single Responsibility Principle all the time, I have to say that the concept is familiar to all of us. If we can name something succinctly then we probably hit upon a single responsibility. If a class or a method is difficult to name then it indicates we’re either unclear on its purpose or that it has too many responsibilities.
Why are having too many responsibilities a bad thing? The answer is that the more responsibilities a class has, the more potential there is to couple to it for orthogonal reasons. As soon as I have multiple reasons to access a class, I have multiple classes using a class that have nothing to do with each other and when the class being used has to change, it often has unexpected side effects on the other classes that use it. By following the Single Responsibility Principle, I have much less opportunity to make this mistake.
Previous Post: « Don’t Test Private Methods
Next Post: How Open-Closed are you? »