Monday, October 20, 2014


Single Responsibility Principle (SRP) says that "Each context should have only one responsibility."
This is simple to understand, but it is too ambiguous to actually apply it in practice. The major reason why is the word "responsibility". In original, Martin defines it as "reason for change", but that doesn't make things clearer. The problem is that responsibilities exist at many different levels of abstraction and in many different contexts. Responsibility can be "Responsibility to print a report", through "Responsibility to execute this query" to "Responsibility to add those two numbers". If this principle was followed rigorously, the code would end up as many tiny classes or functions each having  extremely simple and low-level responsibility.

SRP represents much more important concepts and those are cohesion and coupling. Other set of principles (GRASP) say, that cohesion should be high while number of coupling should be low.

But those two go against each other, so it is key to balance those two in equilibrium. Following SRP rigorously would then result in low cohesion and high coupling. Resulting in something that should be avoided.

One good areas where SRP is good fit is business modeling. It is much easier to use SRP on business responsibilities, than trying to come up with your own.

In light of this, I believe that SRP only serves to remind us, that we should always look at how cohesive and coupled our code is and separate or combine classes or methods based on that.

No comments:

Post a Comment