SOLID: Five Simple Principles That Make Code Better
SOLID is a set of 5 object-oriented design principles that help make software easier to understand, maintain, test, and extend.
- S - Single Responsibility - One class, one job
- O - Open/Closed - Extend without modifying existing code
- L - Liskov Substitution - Subtypes should work like their parent
- I - Interface Segregation - Don't force unnecessary methods
- D - Dependency Inversion - Depend on abstractions, not concrete classes
S — Single Responsibility Principle
A class should have one responsibility. A class should ideally have one reason to change.
Bad:
Employee
- Calculate salary
- Save employee to database
- Send email
These are three different responsibilities.
Better:
Employee
- SalaryCalculator
- EmployeeRepository
- EmailService
Think: One class → one job.
O — Open/Closed Principle
Software should be open for extension but closed for modification.
You should be able to add new behavior without constantly changing existing, tested code.
Example:
Payment
- CreditCardPayment
- PayPalPayment
- ApplePayPayment
Adding ApplePayPayment shouldn't require rewriting the existing payment logic.
Think: Add new behavior without breaking old behavior.
L — Liskov Substitution Principle
It states that a subclass must be usable in place of its parent class without breaking the program.
If:
Bird
↓
Penguin
and Bird assumes every bird can fly, then making Penguin inherit that behavior creates a problem.
Better modeling separates the capabilities:
Bird
- FlyingBird
- Eagle
- Sparrow
- Penguin
Think: A subtype should genuinely behave like its parent.
I — Interface Segregation Principle
Don't force a class to implement methods it doesn't need.
One huge interface:
Employee
- work()
- eat()
- drive()
- fly()
A normal employee shouldn't have to implement fly().
Split interfaces:
- Workable
- Eatable
- Drivable
- Flyable
A class implements only what it actually needs.
Think: Small, focused interfaces are better than huge interfaces.
D — Dependency Inversion Principle
High-level code should depend on abstractions, not concrete implementations.
High-level modules (business logic) must not rely directly on low-level modules (database tools, network calls).
OrderService
↓
MySQLDatabase
(OrderService is tightly tied to MySQL.)
Database
Interface
↑
┌─────┴─────┐
↓ ↓
MySQL SQLServer
↑
│
OrderService
(OrderService depends on the Database interface, not directly on MySQL.)
Think: Depend on what something does, not exactly how it does it.
Easy way to remember
- S → Single job
- O → Open to extension
- L → Like the parent
- I → Interfaces should be small
- D → Depend on abstractions
SOLID is primarily an object-oriented software design principle set—not a complete system-design methodology.
Comments
Post a Comment