SRP: Single Responsability Principle

Hicham BEN KACHOUD
3 min readMar 29, 2022

--

Definition & Example

Introduction

In the previous article , I introduce the Design & Component principles.

For the SOLID Design Principles, there are five: Single Responsibility principle, Open-Closed principle, Liskov Substitution principle, Interface Segregation principle and Dependency Inversion principle.

In this article, i will explain the first one : Single Responsibility Principle.

Definition

A class or function should only be modified for one raison. For that it should do just one and only one thing.

If a class do many things at the same time, you will have to modify it at the little evolution. So you risk causing bugs in features that you didn’t even want to modify.

Example

Imagine we are going to implement an ordering system with invoicing mechanism. We should add the item to the cart if the stock is available, saving in database, creating and sending invoice via email.

The following two pictures represente the two classes: Item & Stock.

NB: The code is on PHP 8

Item.php
Stock.php

Now look at the following class ShoppingCart and tell me what is wrong for you?

ShoppingCart.php

The code above manipulate many things: add to / remove from cart, generate the invoice & send it via email notification. The implementation works fine.

But the problem is if any time I modify the invoice mechanism, I should modify the shoopingCart class and this may cause problems and bugs.

So we should separate the invoice from the shoopingCart System.

For that I create 3 services:

  • EmailService: For sending emails (invoice)
EmailService.php
  • PrintingService: For printing any text: in our case the text represent the invoice.
PrintingService.php
  • InvoiceService: For generating invoice and using the both Printing and Email Services.
InvoiceService.php

We can test the example using the code bellow:

Demo.php

Important

Make sure to not over simplify the code. Don’t take the SRP to the extreme by creating classes with just one function and when your.

Therefore, the SRP is an important rule to make your code more understandable but don’t use it as your programming bible.

Conclusion

The SRP is one of the most used Design Principles in OOP. You can apply it to classes, function or software components.

To follow this principle, the class / function are not allowed to do more than one thing. This avoids any technical coupling between responsibilities and reduces the chang that you need to apply to your class.

--

--

Hicham BEN KACHOUD
Hicham BEN KACHOUD

No responses yet