The SOLID principles are a set of five design principles intended to make software designs more understandable, flexible, and maintainable. They are particularly useful in object-oriented programming.
Definition: A class should have only one reason to change, meaning it should only have one job or responsibility.
Example: A class that handles both database operations and UI logic violates SRP. These responsibilities should be separated into different classes.
Definition: Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.
Example: You can extend functionality by adding new classes or methods rather than modifying existing code. Using interfaces or abstract classes helps achieve this.
Definition: Subtypes must be substitutable for their base types without altering the correctness of the program.
Example: If class Bird
has a method fly()
, then a subclass Penguin
that cannot fly violates LSP. Instead, behaviors should be properly abstracted.
Definition: Clients should not be forced to depend on interfaces they do not use.
Example: Instead of one fat interface with multiple methods, use several smaller, more specific interfaces.
Definition: High-level modules should not depend on low-level modules. Both should depend on abstractions.
Example: Instead of a high-level class directly instantiating a low-level class, both should depend on an interface or abstract class.
Principle | Description |
---|---|
SRP | One class = One responsibility |
OCP | Extend without modifying |
LSP | Derived types must be substitutable |
ISP | Use small, specific interfaces |
DIP | Depend on abstractions, not concretions |
These principles help in writing clean, scalable, and maintainable code. Following SOLID makes it easier to refactor, test, and grow your codebase over time.