Introduction
In this tip, I will explain SOLID Principles that enable software architect to build good designed class in object oriented programming.
Definition
SOLID
- S => Single Responsibility Principle
- O => Open/Close Principle
- L => Liskov Substitution Principle
- I => Interface Segregation Principle
- D=> Dependency Injection Principle
Single Responsibility Principle
This principle means that every class must have one and only one responsibility which means only one task to do and there must be separation of concerns.
For example: Class cannot do validation of inputs and save inputs in database and XML files, then log this. All this is in the same class and same function. This is not valid design in class, there must be separation of concerns.
Open/Close Principle
This means the class must be open to extend its functionality but without hard modification in class.
For example: If you want to make method open to extend but close to modification, you cannot make method virtual method with default implementation and if you want to extend or override this implementation, you can do this by overriding like ToString()
method in C# is virtual
method and you can override its implementation without hard modification of the default code.
Liskov Substitution Principle
This means if class B
is a sub class from A
class, you can substitute and replace child class with base class to add generalization in your code.
Interface Segregation Principle
This means that there must be segregation and separation between structure of class and implementation and to do that, use Interface or data contract that is used to define structure of class and power point of its functionality such as name of method and its inputs and its output without any implementation. When class wants to implement interface, you can write your logic code without problems and this adds abstraction level and generalization in code.
Dependency Injection Principle
This means that if class depends on another external class or logic must not make this hard in class because this adds problems if you want to change dependencies later and it is difficult to test and maintain. You must inject your dependencies as input to class and if you want to change dependencies objects, just change input parameter.
For example: If you design laptop class and this class depends on another electric source class to run laptop
instead of making this hard implemented in laptop class and set for electric source object in class, you can inject this object and send as parameter to class. That is useful if you want to change electric source object by another power source object like electric from gas engine or from solar power, just inject another object without changing any other thing.