🎯 The SRP Rule
“A class should have only ONE reason to change.”Think of it like workers in a restaurant:
- 👨🍳 Chef - Only cooks food
- 🍽️ Waiter - Only serves customers
- 💰 Cashier - Only handles payments
- 🧹 Cleaner - Only cleans tables
🚨 Spotting SRP Violations
❌ BAD: The God Class
✅ GOOD: Focused Classes
🎮 Real Example: Invoice System
Let’s fix an invoice system step by step:❌ Before: One Class Does Everything
✅ After: Each Class Has One Job
🧪 How to Check for SRP Violations
Use these questions:SRP Checklist
SRP Checklist
-
Can you describe the class in one sentence WITHOUT using “and”?
- ✅ “This class stores user data”
- ❌ “This class stores user data AND sends emails”
-
If you need to change one feature, do you touch multiple unrelated methods?
- ✅ Changing email format only touches EmailService
- ❌ Changing email format requires editing UserManager
-
How many reasons could this class change?
- ✅ One reason (e.g., business rules for orders)
- ❌ Multiple reasons (email format, database schema, logging format…)
-
Could you easily test this class in isolation?
- ✅ UserRepository can be tested with just a mock database
- ❌ UserManager needs mock database, mock email server, mock logger…
-
Would a team member understand the class purpose immediately?
- ✅ “InvoicePrinter” - obviously prints invoices
- ❌ “InvoiceManager” - does it manage? print? email? save?
💡 Common SRP Violations & Fixes
🏋️ Practice Exercise
Challenge: Fix the BookStore Class
Challenge: Fix the BookStore Class
This class violates SRP. Split it into focused classes:
📝 Key Takeaways
One Job Only
Each class should have only ONE reason to change
No 'AND' Description
If you use “and” to describe it, split it up
Easy to Test
Focused classes are easy to test in isolation
Easy to Name
Good names describe exactly what the class does
Interview Insight
SRP in LLD interviews: When you present a class diagram, interviewers mentally check if each class has a single, clear responsibility. The most common mistake candidates make is creating a “God class” — a
BookingManager that handles reservation logic, payment processing, email notifications, and database persistence all in one. Instead, separate these into ReservationService, PaymentService, NotificationService, and BookingRepository. When the interviewer asks “what happens if we need to switch from email to push notifications?”, you can say “only the NotificationService changes.” That one sentence demonstrates SRP understanding. The rule of thumb: if a class name ends in “Manager” or “Handler” and has more than 5-6 methods, it probably violates SRP.🏃 Next: Open/Closed Principle
Now that your classes are focused, let’s learn how to add features WITHOUT changing existing code!Continue to Open/Closed Principle →
Learn how to extend your code without modifying it!