The SOLID principles are a set of five design principles in object-oriented programming that aim to create more understandable, flexible, and maintainable code. SOLID principles were first introduced by Robert C. Martin in his 2000 paper Design Principles and Design Patterns.
SOLID principles creates:
- More understandable and maintainable code
- Greater flexibility and easier extension
- Robust and reliable software
Each letter in the SOLID acronym stands for a different principle.
S- SRP / Single Responsibility PrincipleO- OCP / Open-Closed PrincipleL- LSP / Liskov Substitution PrincipleI- ISP / Interface Segregation PrincipleD- DIP / Dependency Inversion Principle
A class should have only one reason to change.
Example: Consider a Customer class that handles both customer data storage and sending email notifications. To follow SRP, split it into separate classes: one for data storage and another for email notifications.
Software entities (classes, modules, functions) should be open for extension but closed for modification.
Example: Instead of modifying existing code, create new classes or methods to extend functionality. For instance, use inheritance or interfaces to add new payment methods without altering existing payment processing code.
Objects of a superclass should be replaceable with objects of a subclass without affecting program correctness.
Example: If you have a Bird superclass, any subclass (e.g., Sparrow, Penguin) should be able to replace it without breaking the program’s behavior.
Clients should not be forced to depend on interfaces they don’t use.
Example: Suppose you have an Employee interface with methods like work() and takeVacation(). Split it into smaller interfaces like Workable and Vacationable so that clients can implement only what they need.
High-level modules should not depend on low-level modules; both should depend on abstractions.
Example: Instead of directly coupling high-level business logic with low-level database access, use an interface or abstract class as an intermediary layer.