Single Responsibility 💻Principle

R M Shahidul Islam Shahed
4 min readAug 18, 2023

The Single Responsibility Principle (SRP) is one of the SOLID principles of object-oriented design. It states that a class should have only one reason to change, meaning that a class should have only one responsibility. In other words, a class should have only one job or function within the software system.

Single Responsibility Principle

The principle aims to improve the maintainability and readability of the codebase by ensuring that each class has a clear and focused purpose. When a class has multiple responsibilities, changes to one of those responsibilities can inadvertently affect other parts of the system, leading to a cascade of changes and potential bugs.

Here’s an example to illustrate the Single Responsibility Principle:

// Not following SRP
class Customer
{
public void AddCustomerToDatabase() { /* ... */ }
public void GenerateInvoice() { /* ... */ }
}

// Following SRP
class Customer
{
public void AddCustomerToDatabase() { /* ... */ }
}

class InvoiceGenerator
{
public void GenerateInvoice() { /* ... */ }
}

In the non-SRP example, the Customer class has both the responsibility of adding a customer to the database and generating an invoice. This violates the SRP, as a change to the invoice generation logic could impact the customer addition functionality.

--

--

No responses yet