DEV Community

Paul Edward
Paul Edward

Posted on

The Solid Design Principle — Single Responsibility

The Solid Design Principle — Single Responsibility

In this series, we’re going to discuss the five Solid Principle, this is actually applied to all Object-Oriented Programming, not just PHP

The five solid designs are listed below

S — Single Responsibility

O — Open/Close

L — Liskov Substitution

I — Interface Segregation

D — Dependency Inversion

So in this write up I will be writing about the S

S — Single Responsibility

This state that a class should have only one reason to change, in simpler terms, a class should only have one task or one responsibility so if there are any other methods in a class that deals with something completely different, that method should be extracted and put somewhere else and your class should have one task/job/responsibilities

Why The Need For Single Responsibility

if we keep our classes just with one responsibility, it does the following

  1. Makes the class easier to maintain.

  2. Potentially make class reusable ( depending on whatever your class is dealing with)

  3. Easier to test

    The point of the User Class above is to save a record to the database and if something goes wrong, an error message is been logged to the file and here are the methods Create, Edit and logError

Now the above class breaks the single responsibility principle because it has more than one responsibility or task, and the reason for this is because of the method logError. Create and Edit Method has perfect reasons to stay in the User Class, it actually performs actions upon the User but the logError does otherwise

So how do we fix this?

We can extract the logError method and keep it in its own class,

*<?php

class *Logger {
    *public function *writeToFile($message){
        *//Write To File
    *}
}
Enter fullscreen mode Exit fullscreen mode

we can also have flexible and expandable enough for it to save to file or save to external resource so if we still need the LogError method then use dependency injection to inject it into the User Class



Thanks for reading, I hope this clears any questions on responsibility principle, if you have any question, simply drop a comment below

Top comments (0)