DEV Community

Walter Nascimento
Walter Nascimento

Posted on

Single Responsibility Principle (SRP)

The Single Responsibility Principle (SRP) is the first of the five SOLID principles and states that a class should have only one reason to change. In other words, a class must have a single responsibility within the system, that is, it must do only one thing and do it well. When a class has multiple responsibilities, it becomes difficult to understand, modify, and maintain. By adhering to SRP, classes become more cohesive, specialized and focused on a single task, which results in cleaner and easier to maintain code.

Example Before Applying SRP in PHP:

class Order {
    private $items;
    private $client;

    public function addItem($item) {
        // logic for adding an item to the order
    }


    public function sendEmailConfirmation($client) {
        // logic to send an order confirmation email to the customer
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, the Order class has three responsibilities: adding items to the order, calculating the order total, and sending a confirmation email. This violates the SRP as the class has more than one reason to change.
โ€‹

Example After Applying SRP in PHP:

class Order {
    private $items;

    public function addItem($item) {
        // logic for adding an item to the order
    }
}

class EmailService {
    private $client;

    public function sendEmailConfirmation($client) {
        // logic to send an order confirmation email to the customer
    }
}
Enter fullscreen mode Exit fullscreen mode

In this refactored example, the Order class now only has the responsibility of managing the order items and calculating the total. The responsibility for sending confirmation emails has been moved to the EmailService class, which now has the sole responsibility for handling sending emails.

This separation of responsibilities makes the code clearer, more cohesive, and easier to maintain. Furthermore, by following SRP, it is simpler to make changes to a single part of the system without affecting other parts, thus promoting software flexibility and extensibility.


Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!

๐Ÿ˜Š๐Ÿ˜Š See you later! ๐Ÿ˜Š๐Ÿ˜Š


Support Me

Youtube - WalterNascimentoBarroso
Github - WalterNascimentoBarroso
Codepen - WalterNascimentoBarroso

Top comments (0)