Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

README.md

Single Responsibility Principle (SRP)

📖 What is SRP?

The Single Responsibility Principle (SRP) states:

A class should have only one responsibility (one job) and only one reason to change.

Instead of creating one large class that performs multiple tasks, split the responsibilities into separate classes.


❌ Before (SRP Violation)

The OrderService class performs multiple responsibilities:

  • Place Order
  • Save Order
  • Send Email
  • Generate Invoice
  • Print Receipt

If any one of these features changes, the OrderService class must also change.


✅ After (SRP Followed)

Each responsibility is moved into its own class.

  • OrderService → Coordinates the order process
  • BookingService → Places the order
  • DatabaseService → Saves the order
  • EmailService → Sends confirmation email
  • InvoiceService → Generates and prints invoices

Now every class has only one responsibility.


📂 Project Structure

01-Single-Responsibility-Principle
│
├── before/
│   └── SRP Violation
│
├── after/
│   └── SRP Implementation
│
└── README.md

🎯 Benefits of SRP

  • Cleaner code
  • Easier to understand
  • Easier to maintain
  • Easier to test
  • Easier to extend

💡 Real-World Example

Think of an online shopping application.

Different people have different responsibilities:

  • 📦 Order Team → Places orders
  • 💾 Database Team → Stores data
  • 📧 Email Team → Sends emails
  • 🧾 Billing Team → Generates invoices

Instead of one person doing everything, each person handles one specific task.

Similarly, in software, each class should focus on one responsibility.


🚀 Key Takeaway

One Class = One Responsibility = One Reason to Change