SOLID Principles
🌟 SOLID Principles
SOLID is a set of five object-oriented design principles that help you write clean, maintainable, and flexible code.
S – Single Responsibility Principle (SRP)
One class = One responsibility
✔ A class should do only one job
✔ It should have only one reason to change
Example:
A Book class should only store book data.
Validation should be in another class.
O – Open/Closed Principle (OCP)
Open for extension, closed for modification
✔ You should be able to add new features
✔ Without changing existing code
Example:
Instead of modifying a class, create a subclass to extend behavior.
L – Liskov Substitution Principle (LSP)
Child classes should behave like parent classes
✔ A subclass should be usable wherever the parent class is used
✔ It should not break the program
Example:
A Square should behave like a Rectangle if it extends Rectangle.
I – Interface Segregation Principle (ISP)
No class should be forced to implement methods it doesn’t use
✔ Create smaller, specific interfaces
✔ Avoid “fat” interfaces with many unrelated methods
Example:
Instead of one big Animal interface with walk(), fly(), swim(),
create smaller interfaces like Walkable, Flyable, Swimmable.
D – Dependency Inversion Principle (DIP)
Depend on abstraction, not concrete classes
✔ High-level classes should depend on interfaces, not concrete classes
✔ Makes code flexible and easy to modify/test
Example:
Use interface Database instead of directly using MySQL class.
🌈 SUPER EASY Summary (One Line Each)
| Principle | Meaning |
|---|---|
| S | One class, one job |
| O | Add new things without changing old code |
| L | Subclasses must work like parents |
| I | Many small interfaces > one big interface |
| D | Depend on interfaces, not implementations |
Comments
Post a Comment