SRP (single-responsibility-principle)

img

Single Responsibility Principle (SRP)

The Single Responsibility Principle (SRP) is one of the five SOLID principles of object-oriented design. It states that a class should have only one reason to change, meaning it should have only one job or responsibility. This principle helps in creating more maintainable and understandable code by ensuring that each class or module focuses on a single functionality.

Key Benefits:

  1. Maintainability: With SRP, classes are smaller and focused on a single task, making them easier to understand, modify, and extend.
  2. Reusability: Well-defined responsibilities promote code reuse, as each class encapsulates a distinct piece of functionality.
  3. Testability: Testing is simplified because classes have a single focus, reducing the complexity of unit tests.

Example:

Consider a class Invoice that handles both invoice calculations and printing.

Violation of SRP:

public class Invoice {
    public void calculateTotal() {
        // Code to calculate total
    }

    public void printInvoice() {
        // Code to print invoice
    }
}

Adhering to SRP:

public class Invoice {
    public void calculateTotal() {
        // Code to calculate total
    }
}

public class InvoicePrinter {
    public void printInvoice(Invoice invoice) {
        // Code to print invoice
    }
}

In the second example, the Invoice class is only responsible for calculations, while the InvoicePrinter class handles printing. This separation of concerns makes each class more focused and adheres to the SRP.

img


SRP in Product

SRP Product Wise: Focus on core Feature

Keep product focus on the core feature.

img

-- image from whats app scaling article


Backlinks