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.
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.
Each responsibility is moved into its own class.
OrderService→ Coordinates the order processBookingService→ Places the orderDatabaseService→ Saves the orderEmailService→ Sends confirmation emailInvoiceService→ Generates and prints invoices
Now every class has only one responsibility.
01-Single-Responsibility-Principle
│
├── before/
│ └── SRP Violation
│
├── after/
│ └── SRP Implementation
│
└── README.md
- Cleaner code
- Easier to understand
- Easier to maintain
- Easier to test
- Easier to extend
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.
One Class = One Responsibility = One Reason to Change