Solid is a collection of 5 princibles:
- Single responsibility principle.
- Open/closed principle.
- Liskov substitution principle.
- Interface segregation/seperation principle.
- Dependency inversion principle.
Single Responsibility Principle (SRP)
Principle: A class should have only one reason to change.
A responsibility is a family of functions that serves one particular actor.
What are the actors?
Actors are the source for the changes.
- Domain Logic
- UI representation
- Object creations
Open/Closed principle (OCP)
Principle: Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.
- Design should be by contract Interfaces
- Classes should hold refrence to Abstract Interfaces and not to Concrete objects.
- Adding new functionality shouldnt require us to change exisiting classes.
How to extend a class:
- Inheritance, Create Subclasses
- Composition, Strategy and Delegation
How to apply OCP:
- OCP by Composition:
- Use Strategy And Delegate patterns,
- Class has a refrence to an Interfaces and Abstract Classes Instead of Concrete classes and forward calls to them.
- OCP by Inheritance: Class methods accepts Interfaces and Abstract Classes.
- Use Template Method Pattern (Abstract Classes With Skeleton method)
Liskov Substitution Principle (LSP)
Principle: Functions that use objects of a Base class must be able to use objects of the Derived classes.
- If you have a base class BASE and subclasses SUB1 and SUB2, the rest of your code should always refer to BASE and NOT SUB1 and SUB2
- You should be able to use a super class in the place of a subclass.
Inerface Segregation/Seperation Principle (ISP)
Principle: clients should not be forced to depend on interfaces they dont use.
- If you have an abstract class or an interface, then the implementers should not be forced to implement parts that they don't care about.
- Make your Interfaces and Abstract classes as cohesive as possible.
Dependency Inversion Principle (DIP)
AKA Dipendency injection, Inversion of control)
Principle: - High level objs should not depend on low level objs, they should depend on abstraction of the lower level. - Abstraction shouldnt depend on details, details should depend on abstraction. - following DIP makes you follow most of the SOLID
- Always create Abstraction for the lower level (adapter).
- High level depends on abstraction of the Lower levels.
- By creating Abstraction of lower level, you bring lower level abstraction to higher abstraction.
- Abstraction depends on Abstractions and not on concrete.
Dependency Injection (DI)
- Giving an Object its Instance variable of a class
- Through Constructor
- XML and Other Configs