A quick reference to writing scalable, maintainable, and flexible object-oriented code. Five core principles that guide developers toward cleaner architecture and smarter decisions.
When building large-scale applications that need to stand the test of time, having a flexible and adaptable codebase is essential. SOLID is a set of five core design principles in object-oriented programming that guide developers in writing cleaner, more maintainable, and flexible code.
๐ก The word SOLID is an acronym โ each letter maps to one principle. Together they help you make smarter architectural decisions that lead to more robust software.
The Five Principles
S โ Single Responsibility Principle
One class, one job.
A class should have
only one reason to change. In simpler terms โ a class should do one thing and do it well. When a class takes on multiple responsibilities, a change to one can unexpectedly break another.
If you find yourself describing a class with the word "and" โ it probably has too many responsibilities.
O โ Open/Closed Principle
Open for extension, closed for modification.
Software entities โ classes or modules โ should be
extendable without changing existing code. You add new functionality by writing new code, not by editing old code. Commonly implemented using interfaces and abstract classes.
This reduces the risk that a change in one place breaks something that was already working.
L โ Liskov Substitution Principle
Subtypes must be substitutable for their base types.
If class B is a subclass of class A, you should be able to
replace A with B without breaking the program. A subclass should honour the behaviour expected of its parent โ not override it in ways that cause errors.
Violations often appear as subclasses throwing exceptions for methods that work fine in the parent class.
I โ Interface Segregation Principle
No code should be forced to depend on methods it doesn't use.
A large, general-purpose interface should be
split into smaller, specific ones. Clients only implement the interfaces they actually need โ keeping things lean and reducing unnecessary coupling.
Many small, focused interfaces are better than one large, bloated one.
D โ Dependency Inversion Principle
Depend on abstractions, not concrete implementations.
High-level modules should not depend on low-level modules โ both should depend on abstractions (interfaces or abstract classes). This makes the code more flexible, easier to maintain, and avoids tight coupling.
If you can swap out a dependency without changing the class that uses it, you've applied DIP correctly.
Wrapping Up
SOLID principles are guidelines, not rules โ apply them with judgement. Over-engineering a simple script in the name of SOLID is worse than writing clean, straightforward code without the acronym.
Used thoughtfully, these principles will help you write code that's easier to test, easier to extend, and much easier for the next person (or future you) to understand. Happy Coding!