SOLID Principles: Scalable Design
SOLID is an acronym for five design principles intended to make software designs more understandable, flexible, and maintainable.
S: Single Responsibility Principle (SRP)
"A class should have one, and only one, reason to change."
- Bad: A
Userclass that saves itself to the database AND formats its own JSON. - Good: A
Userclass for data and aUserRepositoryfor database operations.
O: Open-Closed Principle (OCP)
"Software entities should be open for extension, but closed for modification."
- Idea: You should be able to add new functionality without touching existing code (using interfaces/abstract classes).
L: Liskov Substitution Principle (LSP)
"Objects of a superclass should be replaceable with objects of its subclasses without breaking the application."
- Bad: A
Squareclass inheriting fromRectanglewhere settingwidthalso changesheight(violating expectations of a rectangle).
I: Interface Segregation Principle (ISP)
"No client should be forced to depend on methods it does not use."
- Idea: Many small, specific interfaces are better than one giant, generic interface.
D: Dependency Inversion Principle (DIP)
"Depend on abstractions, not on concretions."
- Idea: High-level modules should not depend on low-level modules. Both should depend on interfaces.
Dependency Injection (DI)
DIP is often implemented using Dependency Injection. Instead of a class creating its own dependencies (new Database()), they are "injected" through the constructor.