Single Responsibility Principle (SRP)

Verze:

02. 07. 2025

Zodpovědná osoba:

Dominik Šlechta

Rule

A class should have only one reason to change, meaning it should have a single responsibility or task.

Description

The Single Responsibility Principle (SRP) states that each class in your application should be responsible for only one part of the functionality. This reduces complexity and makes the class easier to maintain and extend. By focusing on just one responsibility, classes become more modular, which improves their testability and reusability.

Benefits

  • Simplifies Maintenance: Changes are easier to make without affecting other parts of the system.

  • Improved Testability: It's easier to write tests for classes with a single responsibility.

  • Better Modularity: Classes become more reusable across different contexts.

Example (Correct):

class UserValidator {
    public function validate($user) {
        // Validation logic
    }
}

Example (Incorrect):

class UserManager {
    public function validateUser($user) {
        // Validation logic
    }

    public function createUser($user) {
        // User creation logic
    }

    public function sendEmail($user) {
        // Email sending logic
    }
}