OOP and SOLID · core
Single responsibility principle
A class should have one reason to change. A class that calculates tax, renders a PDF, saves to the database and sends email has four reasons to change and cannot be tested alone.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- SRP is about reasons to change, not about one method per class. Tax rules, output format, storage and email change for different reasons.
- Split a god class by responsibility: InvoiceCalculator with a TaxPolicy, InvoiceRenderer, InvoiceRepository, and a notifier. An InvoiceService only orchestrates them.
- Pass the parts in through the constructor. Then tax can be tested with plain numbers, with no database and no email.
- Business rules such as GST rates belong in a named policy or in data, not in a comment or an inline number.
- Look for other bugs in such a class: connections never closed (use try-with-resources or a pool), credentials and SQL inline, email sent even when the insert fails, and throws Exception that hides what can fail.
- Balance: do not split into ten tiny classes. Group things that change together.
- When you criticise a class, name the responsibilities. Saying "it is too long" is not an answer.
- Cleaning a real god class: find the hot, risky parts from history and bugs, add characterisation tests first, extract classes by responsibility behind interfaces in small pull requests, and move callers over step by step. Do not rewrite from scratch.
The red pen
Common traps: mistake → fix
Mistake: Splitting by technical layer alone fixes it
Fix: the tax rule can stay hard-coded inside one layer; split by reason to change.
Mistake: SRP means each class has one method
Fix: it means one reason to change, which can be several methods.
Mistake: Long class equals SRP violation
Fix: a long class with one responsibility is fine.
Easy to hard
Questions interviewers ask, easy to hard
- What is the single responsibility principle?
- This InvoiceService calculates, renders, saves and emails. What is wrong and how do you fix it?
- How can you tell two things are separate responsibilities?
- Can SRP be taken too far?
- A 3000-line OrderManager keeps breaking and features must still ship. How do you clean it up?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.