SOLID¶
The acronym 𝗦𝗢𝗟𝗜𝗗 stands for:
- Single responsibility principle
- Open/closed principle
- Liskov substitution principle
- Interface segregation principle
- Dependency inversion principle
The principles¶
- 𝗦𝗶𝗻𝗴𝗹𝗲 𝗥𝗲𝘀𝗽𝗼𝗻𝘀𝗶𝗯𝗶𝗹𝗶𝘁𝘆 𝗣𝗿𝗶𝗻𝗰𝗶𝗽𝗹𝗲 (𝗦𝗥𝗣)
A class should have only one reason to change. In other words, a class should have a single, well-defined responsibility. That class should entirely encapsulate responsibility.
- 𝗢𝗽𝗲𝗻/𝗖𝗹𝗼𝘀𝗲𝗱 𝗣𝗿𝗶𝗻𝗰𝗶𝗽𝗹𝗲 (𝗢𝗖𝗣)
Software entities (classes, functions, etc.) should be open for extension but closed for modification. You should be able to add new functionality to a class without changing its existing code, but you should not need to modify the class itself to do so.
- 𝗟𝗶𝘀𝗸𝗼𝘃 𝗦𝘂𝗯𝘀𝘁𝗶𝘁𝘂𝘁𝗶𝗼𝗻 𝗣𝗿𝗶𝗻𝗰𝗶𝗽𝗹𝗲 (𝗟𝗦𝗣)
Subtypes must be substitutable for their base types. In other words, if a class is derived from another class, you should be able to use the derived class in the same way as the base class without any issues.
- 𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲 𝗦𝗲𝗴𝗿𝗲𝗴𝗮𝘁𝗶𝗼𝗻 𝗣𝗿𝗶𝗻𝗰𝗶𝗽𝗹𝗲 (𝗜𝗦𝗣)
Clients should not depend on interfaces they do not use. This means you should design your interfaces as specific and focused as possible.
- 𝗗𝗲𝗽𝗲𝗻𝗱𝗲𝗻𝗰𝘆 𝗜𝗻𝘃𝗲𝗿𝘀𝗶𝗼𝗻 𝗣𝗿𝗶𝗻𝗰𝗶𝗽𝗹𝗲 (𝗗𝗜𝗣)
High-level modules should not depend on low-level modules. Both should depend on abstractions. Design your software so high-level modules depend on abstractions rather than concrete implementations.