The Wayback Machine - https://web.archive.org/web/20240914142530/https://www.geeksforgeeks.org/single-responsibility-in-solid-design-principle/
Open In App

Single Responsibility in SOLID Design Principle

Last Updated : 31 Oct, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

SOLID principle is an acronym that stands for 5 key principles in software development: 

  • S – Single Responsibility Principle 
  • O – Open Closed Principle 
  • L – Liskov Substitution Principle
  • I – Interface Segregation Principle
  • D – Dependency Inversion Principle
SOLID Design Principle

 

It has become one of the key principles in modern software development to ensure the code is using these SOLID principles. Following are the advantages that offer while using SOLID principles in your software development.

  1. Helps developers to break down complex problems into smaller manageable pieces.
  2. Helps developers to reduce the dependencies on code so that in the future if any one area of the code changes, it won’t impact the other area of the code.
  3. Helps developers to move tightly coupled code or components into a loosely coupled, flexible, and maintainable manner.

Today, we are going to understand how the “Single Responsibility Principle” works in software development. We are going to demonstrate the example with pseudocode so that you can correlate or write in any familiar programming language.

Single Responsibility in SOLID Design Principle

 

As the name suggests, the Single Responsibility principle states 2 key principles.

  1. Your class or method should have only one reason to change.
  2. Your class or method should have only one responsibility to take care of.

So what does that mean actually? While you design your logic in either class or method, you should not be writing all kinds of responsibilities in one place. This will make your code quite complex and unmanageable. It will also be difficult to adjust new changes later as there are high chances it will affect the other functionality and you will end up testing all the functionalities even though it is a smaller change. Let’s take the example below.

Example Class

 

public class Invoice
{
public void AddInvoice()
{
// your logic
}

public void DeleteInvoice()
{
// your logic
}

public void GenerateReport()
{
// your logic
}

public void EmailReport()
{
// your logic
}
}

The class Invoice consists of 4 different methods – AddInvoice(), DeleteInvoice(), GenerateReport(), EmailReport(). As the single responsibility principle says, your class or method should have only one responsibility and only one reason to change, now let’s find out whether the above example satisfies the conditions. If we take a look at the methods, each has a single responsibility. For e.g. The AddInvoice() method is only responsible for adding an invoice to the system, DeleteInvoice() method is only responsible for deleting invoices,s and likewise for GenerateReport() and EmailReport() methods. We can say that methods do satisfy the single responsibility principle. But if you take a look at Invoice class, it is now taking care of multiple responsibilities which are not satisfying the single responsibility principle. So in order to satisfy the single responsibility principle for class Invoice, we will divide the methods into different classes where one class will take care of only one responsibility.

 

We are going to club methods AddInvoice() and DeleteInvoice() into single class Invoice as they do a similar kind of functionality. Whereas we will be creating separate classes Report and Email for methods GenerateReport() and EmailReport() respectively as they are completely independent and have different functionality. 

 

public class Invoice
{
public void AddInvoice()
{
// your logic
}

public void DeleteInvoice()
{
// your logic
}
}

public class Report
{

public void GenerateReport()
{
// your logic
}
}

public class Email
{
public void EmailReport()
{
// your logic
}
}

That’s it! Now each class is responsible to take care of only one responsibility and only one reason to change. The code is now ever smaller and manageable for each functionality and you won’t be required to test the complete functionality of each class if the change is happening for any one of the classes.

Conclusion

With the above example, we have now understood how to refactor the code and achieve the single responsibility principle. With the help of the single responsibility principle, it helps us to reduce the complexity of the program and easier to maintain the code.



Similar Reads

Dependency Inversion Principle (SOLID)
Let's understand one of the key principles of SOLID principles group namely, Dependency inversion principle. Dependency inversion principle is one of the principles on which most of the design patterns are build upon. Dependency inversion talks about the coupling between the different classes or modules. It focuses on the approach where the higher
3 min read
CQRS - Command Query Responsibility Segregation Design Pattern
The Command Query Responsibility Segregation (CQRS) design pattern has emerged as a powerful architectural pattern for building complex and scalable software systems. By separating the responsibilities of reading and writing data, CQRS allows for more flexible and efficient designs, particularly in domains with high-performance and scalability requ
9 min read
Chain of Responsibility - Python Design Patterns
Chain of Responsibility method is Behavioral design pattern and it is the object-oriented version of if ... elif ... elif ... else and make us capable to rearrange the condition-action blocks dynamically at the run-time. It allows us to pass the requests along the chain of handlers. The processing is simple, whenever any handler received the reques
4 min read
Chain of Responsibility Method Design Patterns in C++
Chain of responsibility Pattern or Chain of Responsibility Method is a behavioral pattern, which allows an object to send a request to other objects without knowing who is going to handle it. This pattern is frequently used in the chain of multiple objects, where each object either handles the request or passes it on to the next object in the chain
8 min read
Chain of Responsibility Design Pattern
The Chain of Responsibility design pattern is a behavioral design pattern that allows an object to pass a request along a chain of handlers. Each handler in the chain decides either to process the request or to pass it along the chain to the next handler. Important Topics for the Chain of Responsibility Design Pattern What is the Chain of Responsib
9 min read
Chain of Responsibility Design Pattern in Java
The Chain of Responsibility Design Pattern in Java is a behavioral design pattern that allows an object to pass a request along a chain of handlers. Each handler in the chain decides either to process the request or to pass it along the chain to the next handler. Important Topics for Chain of Responsibility Design Pattern in Java What is the Chain
9 min read
Chain of Responsibility Method Design Pattern in Javascript
The Chain of Responsibility design pattern in JavaScript allows a request to be passed through a chain of handlers until one processes it. This pattern helps manage complex workflows by decoupling the sender of a request from its receivers, making the system more flexible and easier to extend. In this article, we'll explore how to implement the Cha
6 min read
Class-Responsibility-Collaboration Card
A Class-Responsibility-Collaboration (CRC) card is a structured tool used in object-oriented software design. It captures essential information about a class, including its name, responsibilities, and collaborations with other classes. CRC cards facilitate collaborative discussions among team members and help in refining the design of software syst
12 min read
What is the Difference between Solid and Dotted Line in Sequence Diagram?
In Sequence Diagrams, solid and dotted lines are used to show different kinds of messages between objects. A solid line represents a message where the sender waits for a response from the receiver before continuing.A dotted line represents a message where the sender does not wait for a response and continues right awaySolid Line A solid line repres
2 min read
SOLID Principles in Programming: Understand With Real Life Examples
In software development, Object-Oriented Design plays a crucial role when it comes to writing flexible, scalable, maintainable, and reusable code. There are so many benefits of using OOD but every developer should also know the SOLID principle for good object-oriented design in programming. The SOLID principle was introduced by Robert C. Martin, al
6 min read
Difference between Good Design and Bad Design in Software Engineering
The term design is used in two ways. While used as verb, it means - the design process and used as noun, it means- the result of design process. Design is a meaningful engineering representation of something that is to be built. The result of a design process is called as design model or the design of the system. Design for computer software is as
2 min read
System Design - Design Google Calendar
Google Calendar is like a special calendar that we can use on our computer or phone. We can use it to remember important things, like birthdays, appointments, and events. We can also set reminders to help us remember when something is coming up soon. We can also share our calendars with our family or friends. It's like having our own special schedu
8 min read
How to Design a Rate Limiter API | Learn System Design
A Rate Limiter API is a tool that developers can use to define rules that specify how many requests can be made in a given time period and what actions should be taken when these limits are exceeded. Rate limiting is an essential technique used in software systems to control the rate of incoming requests. It helps to prevent the overloading of serv
11 min read
System Design - Design a Sequencer
Pre-requisites: Logic gates Sequencer is a device that generates a sequence of unique identifiers or numbers. In the context of distributed systems, a sequencer is often used to generate unique IDs and objects across multiple nodes or servers. In this article, we will discuss how to design a sequencer for use in a distributed system. The sequencer
5 min read
Design Principles in System Design
Design Principles in System Design are a set of considerations that form the basis of any good System. But the question now arises why use Design Principles in System Design? Design Principles help teams with decision-making, and is a multi-disciplinary field that involves trade-off analysis, balancing conflicting needs, and making decisions about
5 min read
Design Notification Services | System Design
If we are building an e-commerce application or a booking system or anything of that sort, we will always have a notification service that will be used to notify your consumers. Let us now look at the requirements to build a notification service. Topics for Designing Notification ServicesRequirementsComponentsHow does our system tackle if we want t
8 min read
Design a system that counts the number of clicks on YouTube videos | System Design
Designing a Click Tracking System for YouTube Videos involves architecting a comprehensive and efficient solution to monitor and analyze user interactions with videos on the YouTube platform. Important Topics for Counting the number of Clicks on Youtube Videos System DesignRequirementsCapacity EstimationLow-Level Design (LLD)Database Design-High-Le
15+ min read
Design Facebook's live update of comments on posts | System Design
A live comment system, like Facebook's, works by employing real-time communication technologies, such as WebSockets, to establish a persistent connection between users and the server. When a user posts a comment, it's immediately sent to the server, which then broadcasts the comment to all users viewing the same post in real-time. This allows users
15+ min read
Behavioral Design Pattern | JavaScript Design Pattern
Behavioral design patterns are a subset of design patterns in software engineering that deal with the interaction and responsibilities of objects. These patterns focus on how objects communicate and work together to achieve common tasks. Important Topics for the Behavioral Design Pattern in JavaScript Design Patterns Uses Cases of the Behavioral De
8 min read
Composite Design Pattern | JavaScript Design Patterns
The Composite Design pattern is a way of organizing objects. It helps us handle different objects in a similar way when they are put together to create a structure with parts and wholes. These parts and wholes are like building blocks that can be split into smaller pieces and then put together to make a tree-like structure. The composite design pat
6 min read
Difference between Prototype Design Pattern and Flyweight Design Pattern
The major point in Prototype vs. Flyweight Design Pattern is that Prototype Design Pattern is a creational design pattern whereas Flyweight Design Pattern is a structural design pattern. In this post, we will look into this and more differences between the Prototype and Flyweight Design Patterns. Let us begin with a basic understanding of each of t
2 min read
Facade Design Pattern | JavaScript Design Pattern
Facade design pattern is a Structural design pattern that allows users to create a simple interface that hides the complex implementation details of the system making it easier to use. This pattern intends to create a simplified and unified interface for a set of interfaces hiding the implementation details making it less complex to use. Important
4 min read
Flyweight Design Pattern - JavaScript Design Pattern
The Flyweight Design Pattern is a structural design pattern used in JavaScript to minimize memory usage by sharing the data as much as possible with the related objects. Important Topics for Flyweight Design PatternDiagramatic Representation:Advantages of Flyweight design pattern:Disadvantages of Flyweight design pattern:The shared data typically c
4 min read
Mediator Design Pattern in JavaScript | Design Pattern
The Mediator pattern is a behavioral design pattern that promotes loose coupling between objects by centralizing communication between them. It's particularly useful when you have a complex system with multiple objects that need to interact and you want to avoid the tight coupling that can arise from direct object-to-object communication. Important
5 min read
What is High Level Design – Learn System Design
High-level design or HLD refers to the overall system, a design that consists description of the system architecture and design and is a generic system design that includes: System architectureDatabase designBrief description of systems, services, platforms, and relationships among modules.High-level design or HLD is also known as macro level desig
9 min read
Design a webpage that can show the status of 10M+ users including: name, photo, badge and points | System Design
We've got this huge community—over 10 million strong—and you want to build a webpage where everyone's details, like their names, photos, those cool badges they've earned, and their points, can all be seen. That's a massive load of information to handle. Achieving this goal necessitates an efficient and scalable system architecture capable of handli
15+ min read
Difference between High Level Design(HLD) and Low Level Design(LLD)
System design involves creating both a High-Level Design (HLD), which is like a roadmap showing the overall plan, and a Low-Level Design (LLD), which is a detailed guide for programmers on how to build each part. It ensures a well-organized and smoothly functioning project. High-Level Design and Low-Level Design are the two main aspects of System D
4 min read
Strategy Method Design Pattern | C++ Design Patterns
Strategy Pattern is a behavioral design pattern that defines a family of interchangeable algorithms and allows them to be used interchangeably within a context. This pattern enables the algorithm to be selected at runtime, providing flexibility and promoting code reusability. Important Topics for the Strategy Method in C++ Design Patterns Example o
4 min read
Memento Design Pattern | C++ Design Patterns
Memento Design Pattern is a behavioral design pattern that provides a mechanism for capturing an object's internal state and restoring it to that state at a later time. This pattern is useful when we need to implement features like undo/redo functionality or when we want to save and restore an object's state for various reasons. Important Topics fo
7 min read
System Design Life Cycle | SDLC (Design)
System Design Life Cycle is defined as the complete journey of a System from planning to deployment. The System Design Life Cycle is divided into 7 Phases or Stages, which are:1. Planning Stage 2. Feasibility Study Stage 3. System Design Stage 4. Implementation Stage 5. Testing Stage 6. Deployment Stage 7. Maintenance and Support The system design
7 min read
Article Tags :