Tuesday 14 July 2020

SOLID Design Principles in C# - Liskov Substitution Principle (LSP)



Definition of the Dependency Inversion Principle?

Liskov Substitution Principle (LSP) states "If S is a sub type of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may substitute objects of type T) without altering any of the desirable properties of that program (correctness, task performed, etc.)"

Let's put this in a more simple way. Parent class object should be easily substituted with their child classes object without altering their actual behavior.

In Object Oriented Programming (OOP) parent child mapping will be achieved by Inheritance. If we do not properly utilize the Inheritance then our application would have end up with giving un-expected results. Let's look at the below requirement.

Consider an organization set's working hours for permanent employee is 40 hours and contract employee is 50 hours. Implement a service which should give employee weekly working hours by employee type. 

Permanent Employee Class

Contract Employee Class inherits Permanent Employee Class


Let's try to get the Permanent Employee hours by instantiating the PermanentEmployee.  
 
We will get the valid hours as PermanentEmployee is base class and it is pointing to the same class as well.

Now lets try to get the Permanent Employee salary by pointing derived class instance with the parent class.
This will return the invalid result as Permanent Employee hours set to 40, so here the Inheritance in not working as expected.

What is the solution?

Liskov Substitution Principle (LSP) help's in resolving this issue. By considering LSP let's do the code refactoring which should return a valid working hours for both the employees.

Abstract Class

Inheritance with the abstraction class states it can be derived by other classes and must implement the behaviors (abstract methods) defined in it.

Permanent Employee Class inherits Employee class 

Contract Employee Class inherits Employee class 



An abstract class is base class for which we can not create an object to the abstract class.

 Let's instantiate both Permanent Employee and Contract Employee classes and point or assign the object to the base class which is Employee.
 
Here which ever derived class you are instantiating and adding the reference to the base class the respective derived class methods will be called and returns the actual behavior of the derived classes methods.

Conclusion 

By following the Liskov Substitution Principle (LSP) we can achieve the  best results out of the application.

Please check my below posts on other SOLID principles for better understanding

Single Responsibility Principle (SRP)

Open/Closed Principle (OCP)

Interface Segregation Principle (ISP)