Dezign Patterns

Single Responsibility Principle (SRP)

📜 Definition : A class should have only one reason to change.
🎯 Intent : Each class should do only one job, so that the code should be cleaner and maitainable
✅ Good example : One responsibility is given to InvoicePrinter and InvoiceSaver.

 class InvoicePrinter {
     void printInvoice(Invoice invoice) {
         // handles printing only
     }
 }

 class InvoiceSaver {
     void saveToDB(Invoice invoice) {
         // handles saving only
     }
 }
 

❌ Single Responsibility Principle Violation Example

🧠 General Rule of Thumb:
If your class has multiple functionalities inside a class, it's probably violating SRP. 👀

Mixing printing, saving, and calculations all in one Invoice class.


 class InvoicePrintingAndSaving {
     void saveToDB(Invoice invoice) {
         // handles saving only
     }
     void printInvoice(Invoice invoice) {
         // handles printing only
     }
 }
 
🛒 Real-World Analogy: Online Shopping
  • Order class: stores order info
  • OrderValidator class: checks if order is valid
  • OrderService class: processes the order
  • InvoiceGenerator class: prints or emails the invoice
  • Each one has a single job — and follows SRP perfectly