Table of Contents
SOLID
SOLID is a set of five object-oriented design principles intended to make code more understandable, maintainable, and extensible. The acronym was coined by Robert C. Martin (Uncle Bob).
S — Single responsibility principle
A class should have only one reason to change. In practice: a class that handles both data persistence and business logic is harder to change than one that does only persistence. When the database schema changes and the business rules change, they change independently, and a class that mixes both needs to change for both reasons.
O — Open/closed principle
A class should be open for extension but closed for modification. Adding new behaviour should be possible without modifying existing code. The classic mechanism is an interface or abstract base class: new behaviour is added by adding a new implementation, not by editing the existing class.
L — [[liskov-substitution-principle|Liskov substitution principle]]
Subtypes must be substitutable for their base types without breaking the program's correctness. If a function accepts a Shape, it should work correctly with any subclass of Shape — Circle, Rectangle, Triangle — without needing to check which one it got. A subclass that violates a contract of the base class (e.g., a ReadOnlyList that extends List but throws on add()) breaks this principle.
I — Interface segregation principle
Clients should not be forced to depend on interfaces they do not use. A large, fat interface that bundles ten methods forces every implementor to implement all ten, even if they only need two. Prefer many small, focused interfaces.
D — Dependency inversion principle
High-level modules should not depend on low-level modules; both should depend on abstractions. Instead of a UserService directly instantiating and calling a MySQLRepository, it should depend on a Repository interface that MySQLRepository implements. This makes UserService testable (you can inject a fake repository) and decoupled from the specific database.
SOLID principles are most relevant to large object-oriented codebases. In small programs or functional code the tradeoffs are different, and strict adherence can produce over-engineered designs.
