SOLID Principles - Single Responsibility Principles

Single responsibility principle gives way for easier software implementation and helps prevent un-expected side effects of future modifications. It is an important rule to make the code more understandable.

Robert C. Martin describes it as:

A class should have one, and only one, reason to change.

Cause and effect

Software requirement would change over time. I have been working with my current organisation for two years and I have been involved with changing the core business flow thrice. We have multiple ui components and business modules. Each new change request would involve changes to the responsibility of at least one component (if not many). If a component has more responsibilities, the likelihood of modifying the component increases. If the component has multiple responsibilities, they are no longer independent of each other.

Sometimes, it so happens that even a simple feature request becomes so complex that changing a component creates more side effects, and requires a lot more testing time than it should have had initially.

It is better to avoid these problems by making sure each component has only one responsibility. If a component has only one responsibility it is easier to explain, understand and maintain. Validation becomes easier, developers can easily write unit tests. It also helps improve the development speed and might reduce the number of bugs.

How to identify a SRP use-case

When we receive a new feature request, in the urge to complete the requirement fast, developers often have the tendency to take the easiest and fastest approach. Which might be to add a method or functionality to the existing code, instead of writing a new class or component. This would result in a class or component to have more than one responsibility. Overtime it would become difficult to maintain the codebase.

We avoid this by asking a simple question before making the change (usually on our white boarding sessions).

What is the responsibility of the class/component/microservice/?

If the answer includes the word "and", then we are most likely breaking the SRP. We usually would re-think the current approach.

We generally tend to associate each class with a certain pet name, we address the class as him/her/their and give a certain role and responsibility. Basically the actor gets a role.

When to avoid

A developer should make sure not to oversimply the code. In extreme cases, a component would have just one function. Which is also not ideal. This would lead to increased dependency injections which would in-turn make the code very unreadable and confusing. Defeating the whole purpose of single responsibility.

Examples