Over a million developers have joined DZone.

The Single Responsibility Principle

DZone 's Guide to

The Single Responsibility Principle

What does “responsibility” really mean in the context of the Single Responsibility Principle?

· Java Zone ·
Free Resource

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.

object oriented programming ,best practices ,design pattens

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}