Notes › OOP
SOLID Principles
Five design principles (by Robert C. Martin) for code that's easy to change, test and extend.
| Letter | Principle | In one line |
|---|---|---|
| S | Single Responsibility | a class should have one reason to change |
| O | Open/Closed | open for extension, closed for modification |
| L | Liskov Substitution | a subclass must work anywhere its parent works |
| I | Interface Segregation | many small interfaces beat one fat one |
| D | Dependency Inversion | depend on abstractions, not concrete classes |
S — Single Responsibility Principle
❌ One class doing everything:
class Invoice {
double calculateTotal() { ... }
void printInvoice() { ... } // formatting changes → edit Invoice
void saveToDatabase() { ... } // DB changes → edit Invoice
void emailInvoice() { ... } // email provider changes → edit Invoice
}
Four different reasons to change; a bug fix in emailing risks breaking totals. ✅ Split by responsibility:
class Invoice { double calculateTotal() { ... } }
class InvoicePrinter { void print(Invoice i) { ... } }
class InvoiceRepository { void save(Invoice i) { ... } }
class InvoiceMailer { void send(Invoice i) { ... } }
"Responsibility" = a reason to change, i.e. one actor/stakeholder — not "one method".
O — Open/Closed Principle
❌ Every new type means editing the same method:
class DiscountService {
double discount(String type, double amt) {
if (type.equals("STUDENT")) return amt * 0.10;
else if (type.equals("FESTIVE")) return amt * 0.20;
// new type → modify this tested code again
return 0;
}
}
✅ Add new behaviour by adding new classes:
interface Discount { double apply(double amt); }
class StudentDiscount implements Discount { public double apply(double a) { return a * 0.10; } }
class FestiveDiscount implements Discount { public double apply(double a) { return a * 0.20; } }
class DiwaliDiscount implements Discount { public double apply(double a) { return a * 0.30; } } // new, nothing edited
class DiscountService {
double discount(Discount d, double amt) { return d.apply(amt); }
}
Achieved with polymorphism — the Strategy pattern.
L — Liskov Substitution Principle
If S is a subtype of T, objects of T can be replaced by S without breaking the program.
❌ The classic trap — Square extends Rectangle:
class Rectangle {
protected int w, h;
void setWidth(int w) { this.w = w; }
void setHeight(int h) { this.h = h; }
int area() { return w * h; }
}
class Square extends Rectangle {
@Override void setWidth(int w) { this.w = w; this.h = w; }
@Override void setHeight(int h) { this.w = h; this.h = h; }
}
void resize(Rectangle r) {
r.setWidth(5); r.setHeight(4);
assert r.area() == 20; // fails for Square: area is 16
}
A square is a rectangle in maths, but not in behaviour. ✅ Fix: don't inherit; share an abstraction instead:
interface Shape { int area(); }
record Rect(int w, int h) implements Shape { public int area() { return w * h; } }
record Square(int side) implements Shape { public int area() { return side * side; } }
Other LSP smells: a subclass that throws UnsupportedOperationException (e.g. Penguin extends Bird with fly()), strengthens preconditions, or weakens guarantees. Fix the bird case with FlyingBird and Bird separately.
I — Interface Segregation Principle
❌ A fat interface forces classes to implement methods they don't need:
interface Worker { void work(); void eat(); void sleep(); }
class Robot implements Worker {
public void work() { ... }
public void eat() { throw new UnsupportedOperationException(); } // 🙁
public void sleep() { throw new UnsupportedOperationException(); }
}
✅ Split into focused interfaces:
interface Workable { void work(); }
interface Eatable { void eat(); }
interface Sleepable { void sleep(); }
class Human implements Workable, Eatable, Sleepable { ... }
class Robot implements Workable { ... }
Clients should not depend on methods they don't use.
D — Dependency Inversion Principle
High-level modules shouldn't depend on low-level modules; both depend on abstractions.
❌ Business logic welded to MySQL:
class OrderService {
private MySqlDatabase db = new MySqlDatabase(); // hard-coded
void place(Order o) { db.save(o); }
}
Can't switch to MongoDB, can't unit-test without a real database. ✅ Depend on an interface and inject the implementation:
interface OrderRepository { void save(Order o); }
class MySqlOrderRepository implements OrderRepository { public void save(Order o) { ... } }
class MongoOrderRepository implements OrderRepository { public void save(Order o) { ... } }
class OrderService {
private final OrderRepository repo;
OrderService(OrderRepository repo) { this.repo = repo; } // constructor injection
void place(Order o) { repo.save(o); }
}
new OrderService(new MySqlOrderRepository());
new OrderService(new FakeOrderRepository()); // in tests
Dependency injection (constructor, setter or framework-based like Spring's @Autowired) is the usual way to apply DIP.
Related principles
- DRY — Don't Repeat Yourself: one source of truth for each piece of knowledge.
- KISS — Keep It Simple: the simplest solution that works.
- YAGNI — You Aren't Gonna Need It: don't build features "just in case".
- Composition over inheritance — prefer HAS-A unless it's a true IS-A.
- Law of Demeter — talk to friends, not strangers (
a.getB().getC().do()is a smell).
Don't over-apply SOLID: ten tiny classes for a 50-line script is worse, not better.
SOLID in interviews
- In LLD rounds (Low-Level Design: Parking Lot), say which principle each design choice follows: "Payment is an interface so new methods can be added without editing ParkingLot — Open/Closed."
- Expect "give a violation and fix it" questions — the examples above are the standard ones.
Interview one-liners
- SRP: one reason to change. OCP: extend without modifying. LSP: subtypes must be substitutable.
- ISP: small, client-specific interfaces. DIP: depend on abstractions; inject dependencies.
- Square extends Rectangle breaks LSP.
- Strategy pattern → OCP; dependency injection → DIP.
- Related: Four Pillars of OOP, Abstract Class vs Interface.