SOLID Principles: Single Responsibility Principle

Niraj Markandey
2 min readJul 29, 2022

--

Hello Everyone!

POST-4 of the series Introduction to software design principles and patterns.

Today’s topic is “SOLID Principles: Single Responsibility Principle”.

As name suggest this principle states that class should have only one purpose. We can also rephrase it by saying class should have only one reason to change.

In below diagram “Order” class has multiple responsibilities like calculating cost, processing payment and send notification to user on order state.

This violates Single responsibility principle. Even though Order class will work perfectly but there are some challenges. The class has lots of functionality and interconnected logic. Because of this it is difficult to write tests. Also in future changing one functionality can lead to breaking something completely unrelated. Thus making it harder to refactor. When this codebase grows it will be difficult to understand what is happening in Order class.

To fix this we have separated functionality to different classes. Class “CostProcesssor” has only one responsibility to calculate cost. Similarly, “PaymentProcessor” takes care of payment and “stateNotifier” notifies state to user.

To summarise, Main advantages of Single Responsibility Principles are

  1. Reducing complexity
  2. Make refactoring and testing easier
  3. Reducing unexpected side effects of future changes.

I would like to remind again we should only apply any design principles if we are getting clear benefits out of it. And Single Responsibility Principle is no exception.

Next Topic in this series will be SOLID Principles: Open/Close Principle.

Previous post Introduction to SOLID principles

I write about design principles and patterns on LinkedIn Please follow me there as well

https://www.linkedin.com/in/niraj-markandey-a6829a73/

--

--

Niraj Markandey

Hi I am a tech enthusiast, working as software developer from 6 years. I am passionate about design patterns and principles. I love to solve complex problems.