Introduction
In this post I would like to cover the Single Responsibility Principle (SRP).
I think that this is the basis of any clean and well designed system.
What is SRP?
The term was introduced by Robert C. Martin.
It is the ‘S’ from the SOLID principles, which are the basis for OOD.
http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)
Here’s the PDF paper for SRP by Robert C. Martin https://docs.google.com/file/d/0ByOwmqah_nuGNHEtcU5OekdDMkk/
From Wikipedia:
…In object-oriented programming, the single responsibility principle states that every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility….
From Clean Code:
A class or module should have one, and only one, reason to change.
So if a class (or module) needs to be modified for more than one reason, it does more than one thing. I.e. has more than one responsibility.
Why SRP?
-
Organize the code
Let’s imagine a car mechanic who owns a repair shop.
He has many many tools to work with. The tools are divided into types; Pliers, Screw-Drivers (Phillips / Blade), Hammers, Wrenches (Tubing / Hex) and many more.How would it be easier to organize the tools?
Few drawers with different types in each one of them?
Or, many small drawers, each containing a specific type?Now, imagine the drawer as the module. This is why many small modules (classes) are more organized then few large ones.
-
Less fragile
When a class has more than one reason to be changed, it is more fragile.
A change in one location might lead to some unexpected behavior in totally other places. -
Low Coupling
More responsibilities lead to higher coupling.
The couplings are the responsibilities.
Higher coupling leads to more dependencies, which is harder to maintain. -
Code Changes
Refactoring is much easier for a single responsibility module.
If you want to get the shotgun effect, let your classes have more responsibilities. -
Maintainability
It’s obvious that it is much easier to maintain a small single purpose class, then a big monolithic one. -
Testability
A test class for a ‘one purpose class’ will have less test cases (branches).
If a class has one purpose it will usually have less dependencies, thus less mocking and test preparing.
The “self documentation by tests” becomes much clearer. -
Easier Debugging
Since I started doing TDD and test-first approach, I hardly debug. Really.
But, there come times when I must debug in order to understand what’s going on.
In a single responsibility class, finding the bug or the cause of the problem, becomes a much easier task.
What needs to have single responsibility?
Each part of the system.
- The methods
- The classes
- The packages
- The modules
How to Recognize a Break of the SRP?
-
Class Has Too Many Dependencies
A constructor with too many input parameters implies many dependencies (hopefully you do inject dependencies).Another way too see many dependencies is by the test class.
If you need to mock too many objects, it usually means breaking the SRP. -
Method Has Too Many Parameters
Same as the class’s smell. Think of the method’s parameters as dependencies. -
The Test Class Becomes Too Complicated
If the test has too many variants, it might suggest that the class has too many responsibilities.
It might suggest that some methods do too much. -
Class / Method is Long
If a method is long, it might suggest it does too much.
Same goes for a class.
My rule of thumb is that a class should not exceed 200-250 LOC. Imports included 😉 -
Descriptive Naming
If you need to describe what your class / method / package is using with the AND world, it probably breaks the SRP. -
Class With Low Cohesion
Cohesion is an important topic of its own and should have its own post.
But Cohesion and SRP are closely related and it is important to mention it here.
In general, if a class (or module) is not cohesive, it probably breaks the SRP.A hint for a non-cohesive class:
The class has two fields. One field is used by some methods. The other field is used by the other methods. -
Change In One Place Breaks Another
If a change in the code to add a new feature or simply refactor broke a test which seems unrelated, it might suggest a breaking the SRP. -
Shotgun Effect
If a small change makes a big ripple in your code. If you need to change many locations it might suggest, among other smells, that the SRP is broken. -
Unable to Encapsulate a Module
I will explain using Spring, but the concept is important (not the implementation).
Suppose you use the @Configuration or XML configuration.
If you can’t encapsulate the beans in that configuration, it should give you a hint of too much responsibility.
The Configuration should hide any inner bean and expose minimal interfaces.
If you need to change the Configuration due to more than one reason, then, well, you know…
How to make the design compliant with the Single Responsibility Principle
The suggestions below can apply to other topics of the SOLID principles.
They are also good for any Clean Code suggestion.
But here they are aimed for the Single Responsibility Principle.
-
Awareness
This is a general suggestion for clean code.
We need to be aware of our code. We need to take care.
As for SRP, we need to try and catch as early as we can a class that is responsible for too much.
We need to always look for a ‘too big method’. -
Testable Code
Write your code in a way that everything can be tested.
Then, you will surly want that your tests be simple and descriptive. -
TDD
(I am not going to add anything here) -
Code Coverage Metrics
Sometimes, when a class does too much, it won’t have 100% coverage at first shot.
Check the code quality metrics. -
Refactoring and Design Patterns
For SRP, we’ll mostly do extract-method, extract-class, move-method.
We’ll use composition and strategy instead of conditionals. -
Clear Modularization of the System
When using a DI injector (Spring), I think that Configuration class (or XML) can pinpoint the modules design. And modules’ single responsibility.
I prefer to have several small to medium size of configuration files (XML or Java) than having one big file / class.
It helps see the responsibility of the module and easier to maintain.
I think that the configuration approach of injection has an advantage of annotation approach. Simply because the Configuration approach put the modules in the spotlight.
Conclusion
As I mentioned in the beginning of this post, I think that Single-Responsibility-Principle is the basis of a good design.
If you have this principle in your mind while designing and developing, you will have a simpler more readable code.
Better design will be followed.
One Final Note
As always, one needs to be careful on how to apply practices, code and design.
Sometimes we might do over-work and make simple things over complex.
So a common sense must be applied at any refactor and change.
Pingback: It’s All About Tests – Part 1 | Learning and Improving as a Craftsman Developer
Hi, Eyal,
Thanks for the clarifications. (Where I make no comment on your point,
I entirely concede that point and thank you for it.)
“My point of view, is that a reason to change would be behavior
change.” Ah. I hadn’t thought of it that way. That’s indeed better.
“In my example, I could have instantiated an ArrayList, but it should
not change the contract: returning a List.” Agreed, and I think this
would have been slightly better because ArrayList does not (that I
remember) have any methods that are not also List methods, whereas
LinkedList does (or at least has many more than ArrayList, for
example: removeFirstOccurrence(), poll(), peekLast(), etc.). But this
was a minor point as the method was perfectly clear.
“I would say that if I have 5 things to improve in the class
(refactoring or similar), the it has 5 reasons to change.” That’s also
interesting. I hadn’t thought of that perspective, either.
“I think I understand your meaning ‘code depth’ but I would appreciate
if you elaborate it.” By ‘code depth’ I just mean the average length
of all transitive dependencies in a system. So, say a System is just 2
methods, a() -> b(). Then the average code depth is 2. If the system
is two transitive dependencies: a() -> b() -> c() and a() -> b() ->
d(), then it has a depth of 3. The figure is not important, just the
feel for how long the transitive dependencies are. In my experience,
the more and the longer the transitive dependencies dependencies in a
system, the worse it is (because it is along these transitive
dependencies that ripple effects run).
I think it is not possible to address ripple effect problems without
addressing transitive dependencies. More specifically, if ripple
effect is when a change in one part of the code causes changes in
another, then it is not obvious to me how SRP reduces the dependencies
on the part of the code being changed.
Of course, I could think up examples where SRP does precisely this,
where it might cause a reduction in dependencies. For example, if a
class has two behaviours – behaviourA and behaviourB – and they both
depend on one another within that class. Let’s say there is only one
class than depends on behaviourA and ten that depend on behaviourB;
but because both behaviours are in the same class and behaviourA
depends on behaviourB, then we can say that all 10 classes that depend
on behaviourB also transitively depend on behaviourA, so that a change
to behaviourA could (in theory) ripple to behaviourB and to all its
dependees, even though they they did not directly depend on
behaviourA.
In this case, splitting the two behaviours in separate classes would
indeed reduce dependencies as the ten classes that depend on
behaviourB would now be totally isolated from behaviourA – AS LONG AS
the mutual dependency between behaviourA and behaviourB was also
severed at the same time.
But I find it hard to credit SRP with the reduction in potential
ripple effect here. I would credit this more to reducing dependencies
between the behaviours, in which case we might as well thank Occam, as
if they could be eliminated then they were superfluous.
I’m not saying SRP is useless, just that I see its benefit more on
semantic level than on the level of syntactic dependency management:
SRP makes classes easier to understand in and of themselves but does
not inherently reduce transitive dependency. (And again, making
classes smaller also makes them easier to understand in and of
themselves.)
I suppose my problem with SRP is that word, “Change,” as in, “One and
only one reason to change.” When I see a principle mentioning, “Reason
to change,” I automatically think that this principle will make a
system easier to change; the only efficient way to do this is to
actively reduce transitive dependencies and I don’t see how SRP does
this any better than a principle saying, “Reduce transitive
dependencies.”
Regards,
Ed
Hi, Eyal,
Thank you for this post and then high-quality of your blog overall.
Whereas this post makes some fine points, I think it’s a shame you
don’t mention one of the criticisms of the SRP: namely that it is
subjective. Few agree what, “One responsibility,” is, so code written
to this principle can find as many detractors as supporters.
Of course, we all have a feeling for what you mean; the principle
sounds good, it’s just that, in practice, it often leads to the type
of disagreement that principles are created to avoid.
The excellent Robert C. Martin has much excellent advice, but – taking
his advice litterally – I have never seen a class with only one reason
to change. In the example you provide in your accompanying slides, you
present class AddAttributeIfNotExists with a constructor taking two
arugments, and two methods: manipulate() and modify(). Isn’t that
straight away four reasons to change: the class name, the number of
constructor agruments, or the name of either method?
And that’s before going into the implementation of either method. For
example, manipulate() has a List argument but returns a LinkedList
implementation: what if any ArrayList implementation is required?
(Indeed, why use a LinkedList implementation if a List is returned?)
And what if some day it’s decided that this class shouldn’t know the
details of Attributes, in that it shouldn’t know that the are
String-pairs, and instead an Attribute is passed in the in constructor
and instead of calling Attribute.containsName() some form of
Attribute.equals() is used, thereby delegating Attribute
equality-checks to the Attribute implementation? Wouldn’t this be
another reason to change?
(Incidentally, does Item.withModifiedAttributes() return the same Item
with modified attributes or a new Item with the modified attributes?
The method name modifyItem() suggests that the Item is mutated, and
withModifiedAttributes() also suggests mutation; but the
implementation of manipulate() suggests it is immutable.)
Almost every line could change in this class. Aren’t these potentially
dozens of reasons to change?
I presume that the spirit of the SRP would say, “Yes, but that’s just
details. On the overall semantic level, this class will only change
for one reason and that is if Attributes that don’t exist are not to
be added,” or something like that, but this is precisely the
high-level semantics that people argue about.
I think AddAttributeIfNotExists is a lovely, small, well-defined,
class, but the only thing that’s not semantic in that description is,
“Small,” and even that is up for grabs. Going further to say that it
has only one reason to change is a step to far for some.
Now for some specific issues with the blog post.
From your, “Why SRP?” section:
– “This is why many small modules (classes) are more organized then few
large ones.” “Organized,” is also a rather ill-defined term.
– “More responsibilities lead to higher coupling.” I would not
necessarily say that this is the case, though I’m not at all a fan of
the phrases, “Coupling and cohesion;” see:
http://edmundkirwan.com/general/c-and-c.html If you mean coupling
between classes, then if a class with 4 responsibilities is decomposed
into 4 classes with 1 responsibility, it could be the case that the
clients of those responsibilities now need to depend on 4 classes
instead of 1, and hence coupling could increase with SRP.
– “The couplings are the responsibilities.” That’s an interesting
idea; I hope you elaborate on that in a post sometime.
– “Higher coupling leads to more dependencies, which is harder to
maintain.” I would have thought that higher coupling is by definition
more dependencies. Is there a sense in which this is not so?
– “Refactoring is much easier for a single responsibility module.” Well,
refactoring of the SRP module might be easier but it is not necssarily
the case that the system will be more easily refactored. If a system
is crawling with transitive dependencies then SRP might make the
system harder to refactor.
– “A test class for a ‘one purpose class’ will have less test cases
(branches).” True but classes are implementation and testing
implementation can lead to brittle tests which increase system
development costs (common practice suggests testing “behaviour” which
is not at all synonymous with a class). And branching relates much
more to transitive dependencies than with any specific class, SRP or
no. So, again, the class’s having fewer branches as a result of SRP is
no guarantee of the system’s having fewer branches.
From your, “How to Recognize a Break of the SRP?” section:
– “If a method is long, it might suggest it does too much.” I agree,
but I this should be rather the point of your blog post than SRP. I
think you could replace the concept of possessing SRP with, “Small,”
in your post of retain 99% of its validity but with the extra bonus
that people immediately know that size is subjective and with the
extra, extra bonus of not creating arguments about what, “One
responsibility,” actually means. Small classes, “Organize the code,”
are, “Less fragile,” have, “Low Coupling,” make, “Code Changes,”
easier, have more, “Maintainability,” and, “Testability,” and enjoy,
“Easier Debugging.” What does SRP bring that smallness does not?
– “If you need to describe what your class / method / package is using
with the AND word, it probably breaks the SRP.” Curious that you
vilify the logical AND, but not the logical IF of the
AddAttributeIfNotExists class that you offer as an example of SRP.
– “If a small change makes a big ripple in your code. If you need to
change many locations it might suggest, among other smells, that the
SRP is broken.” Don’t get me wrong, I believe ripple-effect to be the
Great Enemy of software structure, and I applaud your raising the
issue here, but I don’t see how SRP fights ripple effect. SRP
distributes responsibilites: it does not, as far as I am aware, reduce
dependency on any given responsibility. (Though perhaps I’m
misunderstanding the word, “Locations,” here.) Certainly it can be the
case that an SRP class has 20 dependent classes and when a change to
that single responsibility happens in the SRP class, all 20 classes
might be changed. This ripple-effect does not indicate SRP
violation. I know you say, “Might,” not, “Will,” but do you consider
SRP to be a major contributor to ripple effect? I would say if a small
change makes a big ripple in your code then you definitely have a lot
of dependencies on that changed code but SRP violation would not be a
prime suspect for me.
And all the suggestions you have in section, “How to make the design
compliant with the Single Responsibility Principle,” are excellent,
though I think excellent general recommendations entirely apart from
SRP (I do not think them, “aimed for the Single Responsibility
Principle”).
“As I mentioned in the beginning of this post, I think that
Single-Responsibility-Principle is the basis of a good design.” For
what it’s worth, I disagree (and think – if I were really really
forced to mention one thing that might be the basis of good design,
which I really really hope I never am – I would chose code depth, the
average lenght of transitive dependencies wiring through the
code-base), but I do respect that you wrote with such clarity and
respect.
Thanks again for the blog post,
Ed
PS The excellent Robert C. Martin wrote FitNesse and given that he’s
the author of SRP, I presume he wrote FitNesse with SRP in mind. Do
you think its structure suggests the benefits you derive from SRP:
http://edmundkirwan.com/general/fitnesse.html
PPS I found your blog through your recent Dzone comment, in case you
were wondering.
Hi Ed,
Thank you very much for your input!
Please allow me to response inline.
You ask:
[Whereas this post makes some fine points, I think it’s a shame you
don’t mention one of the criticisms of the SRP: namely that it is
subjective. Few agree what, “One responsibility,” is, so code written
to this principle can find as many detractors as supporters.
Of course, we all have a feeling for what you mean; the principle
sounds good, it’s just that, in practice, it often leads to the type
of disagreement that principles are created to avoid.]
Eyal:
Well, my reason for this post was to describe the SRP and why it’s important (as part of SOLID).
I agree that it can be subjective.
Same as clean code. Some can consider code as clean and others will argue.
But the principal is important.
You write:
[The excellent Robert C. Martin has much excellent advice, but – taking
his advice litterally – I have never seen a class with only one reason
to change. In the example you provide in your accompanying slides, you
present class AddAttributeIfNotExists with a constructor taking two
arugments, and two methods: manipulate() and modify(). Isn’t that
straight away four reasons to change: the class name, the number of
constructor agruments, or the name of either method?]
Eyal
modify() is private method.
It depends of your view of “a reason to change”.
If you take it literally, then each line can be a reason to change 🙂
My point of view, is that a reason to change would be behavior change.
Imagine a similar class that does two things:
1. add attribute if not exists
2. capitalize attribute name if exists
That’s my point
You write:
[And that’s before going into the implementation of either method. For
example, manipulate() has a List argument but returns a LinkedList
implementation: what if any ArrayList implementation is required?
(Indeed, why use a LinkedList implementation if a List is returned?)]
Eyal:
Do you know of any other way to instantiate a List?
The method returns a List. The user of this method knows it gets a List.
The whole point is that we should not care of the implementation.
In my example, I could have instantiated an ArrayList, but it should not change the contract: returning a List.
You write:
[And what if some day it’s decided that this class shouldn’t know the
details of Attributes, in that it shouldn’t know that the are
String-pairs, and instead an Attribute is passed in the in constructor
and instead of calling Attribute.containsName() some form of
Attribute.equals() is used, thereby delegating Attribute
equality-checks to the Attribute implementation? Wouldn’t this be
another reason to change?]
Eyal:
I couldn’t agree with you more about it 🙂
In better abstraction, one should not know how Attribute are implemented.
I guess that once someone refactors Attribute, many classes that use it will have to be changed.
There is hard coupling between the class in the example and the Attribute.
You write:
[(Incidentally, does Item.withModifiedAttributes() return the same Item
with modified attributes or a new Item with the modified attributes?
The method name modifyItem() suggests that the Item is mutated, and
withModifiedAttributes() also suggests mutation; but the
implementation of manipulate() suggests it is immutable.)]
Eyal:
I usually prefer immutability. Perhaps I gave wrong (confusing) names to the methods.
You write:
[Almost every line could change in this class. Aren’t these potentially
dozens of reasons to change?]
Eyal:
I’ll take one more step.
I would say that if I have 5 things to improve in the class (refactoring or similar), the it has 5 reasons to change.
But, as in your next paragraph, the spirit of “one reason to be changed” is due to my point above (capitalize attribute name)
You write:
[I presume that the spirit of the SRP would say, “Yes, but that’s just
details. On the overall semantic level, this class will only change
for one reason and that is if Attributes that don’t exist are not to
be added,” or something like that, but this is precisely the
high-level semantics that people argue about.]
Eyal:
Yes.
You write:
[I think AddAttributeIfNotExists is a lovely, small, well-defined,
class, but the only thing that’s not semantic in that description is,
“Small,” and even that is up for grabs. Going further to say that it
has only one reason to change is a step to far for some.
Now for some specific issues with the blog post.
From your, “Why SRP?” section:]
Eyal:
Most of this part is my opinion, based on experience and reading.
[- “This is why many small modules (classes) are more organized then few
large ones.” “Organized,” is also a rather ill-defined term.]
Eyal:
I guess the mechanic drawers analogy didn’t explained it well.
You write:
[- “More responsibilities lead to higher coupling.” I would not
necessarily say that this is the case, though I’m not at all a fan of
the phrases, “Coupling and cohesion;” see:
http://edmundkirwan.com/general/c-and-c.html If you mean coupling
between classes, then if a class with 4 responsibilities is decomposed
into 4 classes with 1 responsibility, it could be the case that the
clients of those responsibilities now need to depend on 4 classes
instead of 1, and hence coupling could increase with SRP.]
Eyal:
I’ll go with you on that.
If I decomposed a class into 4 “SRP” ones, and all the clients that used the former now use the new ones,
then perhaps that “big” class actually did one thing. Which was be as some kind of service to those clients.
I still think that trying to keep SRP will lead to less coupling.
You write:
[- “The couplings are the responsibilities.” That’s an interesting
idea; I hope you elaborate on that in a post sometime.]
Eyal:
I took it as a note to self to elaborate it one time:)
You write:
[- “Higher coupling leads to more dependencies, which is harder to
maintain.” I would have thought that higher coupling is by definition
more dependencies. Is there a sense in which this is not so?
– “Refactoring is much easier for a single responsibility module.” Well,
refactoring of the SRP module might be easier but it is not necssarily
the case that the system will be more easily refactored. If a system
is crawling with transitive dependencies then SRP might make the
system harder to refactor.]
Eyal:
Even if we take your argument from the beginning, let’s say we improve the abstraction of Attribute, hence, need to change AddAttributeIfNotExists.
It should be fairly easy as it uses Attribute only in few places.
If it had done more things with Attribute, then we would have needed to modify it more.
And its tests as well.
You write:
[- “A test class for a ‘one purpose class’ will have less test cases
(branches).” True but classes are implementation and testing
implementation can lead to brittle tests which increase system
development costs (common practice suggests testing “behaviour” which
is not at all synonymous with a class).]
Eyal
Agree.
You write:
[And branching relates much
more to transitive dependencies than with any specific class, SRP or
no. So, again, the class’s having fewer branches as a result of SRP is
no guarantee of the system’s having fewer branches.]
Eyal:
Can you elaborate “transitive dependencies”?
If I take my example above (capitalize attribute), then the test class of the behavior of the class will have more tests.
Actually, this is something that I had pains many times.
I get smells of not SRP by seeing test classes that has many asserts (not just the data of a BO response class).
Also, sometimes when I need to setup a-lot in a test, I find that the class breaks the SRP.
And, if we say that test should test behavior and not implementation, then breaking the SRP means testing many behaviors.
You write: [From your, “How to Recognize a Break of the SRP?” section:]
Eyal: My points in this section are some smell recommendations.
You write:
[- “If a method is long, it might suggest it does too much.” I agree,
but I this should be rather the point of your blog post than SRP. I
think you could replace the concept of possessing SRP with, “Small,”
in your post of retain 99% of its validity but with the extra bonus
that people immediately know that size is subjective and with the
extra, extra bonus of not creating arguments about what, “One
responsibility,” actually means. Small classes, “Organize the code,”
are, “Less fragile,” have, “Low Coupling,” make, “Code Changes,”
easier, have more, “Maintainability,” and, “Testability,” and enjoy,
“Easier Debugging.” What does SRP bring that smallness does not?
– “If you need to describe what your class / method / package is using
with the AND word, it probably breaks the SRP.” Curious that you
vilify the logical AND, but not the logical IF of the
AddAttributeIfNotExists class that you offer as an example of SRP.]
Eyal:
I have to say that you took it to the extreme 🙂
The ‘if’ in this class explains what it does. That’s what I think…
You write:
[- “If a small change makes a big ripple in your code. If you need to
change many locations it might suggest, among other smells, that the
SRP is broken.” Don’t get me wrong, I believe ripple-effect to be the
Great Enemy of software structure, and I applaud your raising the
issue here, but I don’t see how SRP fights ripple effect. SRP
distributes responsibilites: it does not, as far as I am aware, reduce
dependency on any given responsibility. (Though perhaps I’m
misunderstanding the word, “Locations,” here.) Certainly it can be the
case that an SRP class has 20 dependent classes and when a change to
that single responsibility happens in the SRP class, all 20 classes
might be changed. This ripple-effect does not indicate SRP
violation. I know you say, “Might,” not, “Will,” but do you consider
SRP to be a major contributor to ripple effect?]
Eyal:
No.
In my experience ripple effect will usually be because of less abstraction (the Attribute example above) or coupling.
You write:
[I would say if a small
change makes a big ripple in your code then you definitely have a lot
of dependencies on that changed code but SRP violation would not be a
prime suspect for me.
And all the suggestions you have in section, “How to make the design
compliant with the Single Responsibility Principle,” are excellent,]
Eyal: Thanks.
You write:
[though I think excellent general recommendations entirely apart from
SRP (I do not think them, “aimed for the Single Responsibility
Principle”).]
Eyal:
True.
BTW,
I even think the my accompanying slides are more describing the SOLID principals and some OOD concepts than just the SRP.
You write:
[“As I mentioned in the beginning of this post, I think that
Single-Responsibility-Principle is the basis of a good design.” For
what it’s worth, I disagree (and think – if I were really really
forced to mention one thing that might be the basis of good design,
which I really really hope I never am – I would chose code depth, the
average lenght of transitive dependencies wiring through the
code-base), but I do respect that you wrote with such clarity and
respect.]
Eyal:
I guess I meant that SRP is something basic.
Something as the foundation of other principals.
I think I understand your meaning “code depth” but I would appreciate if you elaborate it.
Kumar: yes it is 🙂
quite a detailed post on SRP.