OOP Principles and SOLID
Use encapsulation, abstraction, inheritance and polymorphism well, and apply the five SOLID principles to keep code easy to extend and test.
Beginner · about 4 hours · difficulty 2/5
Learn first: What System Design Is (HLD vs LLD)
Low-level design is judged on whether your classes are easy to change. Object-oriented principles and SOLID are the vocabulary interviewers use to judge that.
The four OOP pillars
- Encapsulation: keep state private and expose behaviour (account.withdraw(amount), not account.balance -= amount).
- Abstraction: depend on what something does, not how (a PaymentGateway interface).
- Inheritance: reuse through "is-a" relationships. Use sparingly.
- Polymorphism: one interface, many implementations, chosen at runtime (UpiPayment, CardPayment).
Prefer composition over inheritance: a Car has an Engine, rather than Car extends Engine.
SOLID
- S, Single Responsibility: a class has one reason to change. An Invoice class should not also send emails.
- O, Open/Closed: open for extension, closed for modification. Add a new discount type by adding a class, not by editing a giant if-else.
- L, Liskov Substitution: subclasses must work wherever the parent is expected. If Square breaks Rectangle's setWidth behaviour, the hierarchy is wrong.
- I, Interface Segregation: many small interfaces beat one fat one. A Printer should not be forced to implement fax().
- D, Dependency Inversion: high-level code depends on abstractions; concrete classes are injected. This makes testing with fakes easy.
Related ideas
DRY, KISS, YAGNI, high cohesion and low coupling, and dependency injection as the practical tool for D.
Pitfalls
- Deep inheritance trees built to "reuse code".
- Applying every principle everywhere and producing 40 classes for a 200-line problem.
- Anaemic models: classes that are just getters and setters while all logic sits in one manager class.
You are ready to move on when you can refactor a switch statement over payment types into a polymorphic design and name which SOLID principles the refactor satisfies.
Key concepts
- Encapsulation and abstraction
- Inheritance vs composition
- Polymorphism
- Single Responsibility and Open/Closed
- Liskov Substitution
- Interface Segregation and Dependency Inversion
- Dependency injection
- DRY, KISS, YAGNI
Mini project
Write a small discount engine for an e-commerce cart (flat, percentage, buy-one-get-one, bank offer) first as one big function, then refactor it to follow SOLID. Add a new discount type to both versions and compare how many lines you had to touch.
Check yourself
Give an example where using inheritance breaks the Liskov Substitution Principle and show how composition fixes it.
Free resources
- SOLID (Wikipedia)
- Refactoring.Guru (Refactoring.Guru)
- Software design and architecture roadmap (roadmap.sh)