DEV Community

Cover image for SOLID Principles: Single Responsibility Principle (SRP)
Amburi Roy
Amburi Roy

Posted on

SOLID Principles: Single Responsibility Principle (SRP)

🪨 SOLID Principles

SOLID is a list of 5 software engineering principles. It is a meta acronym where each letter corresponds to another acronym:

Without any further ado, let's jump into today's topic:

Single Responsibility Principle (SRP)

Single Responsibility Principle (SRP) is one of the SOLID principles of object-oriented programming.

It states that a class should have only one reason to change, meaning it should have only one responsibility or job. The SRP aims to keep classes focused and well-organized, making them easier to understand, maintain, and extend.

Goal: To encourage a clear and modular design by ensuring that each class or module has a single, well-defined responsibility. This separation of concerns helps in code organization, maintainability, and reducing the risk of bugs when changes are made.

  • Maintainability: Easier maintenance due to isolated changes within classes.
  • Readability: Improved code readability with clear and single responsibilities.
  • Reusability: Enhanced reusability of smaller, focused classes.
  • Testing: Simplified testing with more focused unit tests.

Bad Example:

class PaymentService {
    public function processGooglePayment($amount) {
        // Code to process payment with Google gateway
    }

    public function processApplePayment($amount) {
        // Code to process payment with Apple gateway
    }

    public function refundPayment($paymentMethod, $amount) {
        // Code to issue a refund
    }
}
Enter fullscreen mode Exit fullscreen mode

Here, the PaymentService class violates SRP by handling multiple responsibilities - processing payments with Google and Apple gateways and issuing refunds. This lack of separation makes the class harder to understand, maintain, and test.

Good Example:

class GooglePaymentService {
    public function processPayment($amount) {
        // Code to process payment with Google gateway
    }
}

class ApplePaymentService {
    public function processPayment($amount) {
        // Code to process payment with Apple gateway
    }
}

class RefundService {
    public function refundPayment($paymentMethod, $amount) {
        // Code to issue a refund
    }
}
Enter fullscreen mode Exit fullscreen mode

Here, we've applied SRP by creating separate classes for each responsibility. GooglePaymentService and ApplePaymentService handle payment processing for Google and Apple, respectively, while RefundService deals with refunds. Each class has a single responsibility, making the code more organized and maintainable. This adheres to the Single Responsibility Principle, enhancing code quality and readability.

Top comments (0)