20 Oct 2014

Single responsibility principle - Redefined

Single responsibility principle by Uncle Bob (Robert C. Martin) is the first of the SOLID object orientated design principles. I read it a few years ago, but felt my understanding of it was a little unclear, and I am not alone. This led me to try to understand it again and during which I've discovered that Uncle Bob has redefined it.

UncleBob
 

The old SRP

"A CLASS SHOULD HAVE ONLY ONE REASON TO CHANGE."
 
Bob explains that a responsibility is defined as "a reason for change". If a class has more that one responsibility then those responsibilities become coupled and changes to one may impair the ability to meet the others. This coupling makes the design fragile, with changes causing unexpected impacts in the system.
 
"If you can think of more than one motive for changing a class, then that class has more than one responsibility."
 
When I read this chapter It feels like the focus is the functionality of a class. That it should not have differing sets of functionality, which seems to be no different than cohesiveness.

If you are already aware that concerns such as presentation, persistence and business logic should be separated, then most of the examples people use to describe SRP become redundant. What you have left with is the decision whether breaking up a class is worth the additional complexity.

The new SRP

Bob says that "Things that change for the same reason should be grouped together. Things that change for different reasons should be separated.", this is not new, but he also says:

"A responsibility is a person, not something the code does. It is a person who wants to make a change to the code."

So we now should think about who would require changes to our classes. He clarifies that a person can have more than one role and the role is who the code is responsible to.

"If two different people want to change a class for two different reasons, then pull those reasons into two different classes. That is the SRP."

"Violation of SRP means that a change by one role could affect the code for another role."

Conclusions

Changing the focus away from the functionality of the code to the person/role who want to change it makes the principle a lot clearer for me.

Wikipedia is out of date.

blog comments powered by Disqus

Image attribution: "Ibus and body guards in black suits" by Len Radin is licensed under CC BY 2.0

About Me


My first computer was a Commodore VIC-20, I had great fun trying to code text adventures and side scrolling shoot ‘em ups in BASIC. This helped me lead the way as the first in my school to pass a computer exam.

Currently I work as a Senior Software Engineer in Bedford for a FTSE 100 Company. Coding daily in C#, JavaScript and SQL. Outside of work I work on whatever is interesting me at that time.