SRP: Single Responsability Principle

Introduction

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

Definition

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

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.

Item.php
Stock.php
ShoppingCart.php
  • 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
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.

Conclusion

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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store