Sunday, August 15, 2021

The Single Responsibility Principle

Everyone in software development probably knows the Single Responsibility Principle (SRP) or at least assumes to know it. A common interpretation of this principle is this:

A component should do only one thing, and do it right.

That’s good advice, but not the actual intent of the SRP. “Doing only one thing” is actually the most obvious interpretation of a single responsibility, so it’s no wonder that the SRP is frequently interpreted like this. Let’s just observe that the name of the SRP is misleading. Here’s the actual definition of the SRP:

A component should have only one reason to change.

As we see, “responsibility” should actually be translated to “reason to change” instead of “do only one thing”. Perhaps we should rename the SRP to “Single Reason to Change Principle”. If a component has only one reason to change, it might end up doing only one thing, but the more important part is that it has only this one reason to change.

What does that mean for our architecture?

If a component has only one reason to change, we don’t have to worry about this component at all if we change the software for any other reason, because we know that it will still work as expected. Sadly, it’s very easy for a reason to change to propagate through code via the dependencies of a component to other components.

Figure 1 - Each dependency of a component is a possible reason to change this component, even if it is  only a transitive dependency (dashed arrows).

In the figure above, component A depends on many other components (either directly or transitively) while component E has no dependencies at all. The only reason to change component E is when the functionality of E must change due to some new requirement. Component A, however, possibly might have to change when any of the other components change, because it depends on them.

Many codebases grow harder - and thus more expensive - to change over time because the SRP is violated. Over time, components collect more and more reasons to change. After having collected many reasons to change, changing one component might cause another component to fail.

No comments: