Skip to main content

SOLID - Liskov Substitution - Principle



Liskov Substitution Principle (LSP) can be considered as an extension to OCP. LSP stated that if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e. an object of type T may be substituted with any object of a subtype S) without altering any of the desirable properties of the program (correctness, task performed, etc.). taken from Wikipedia.

On programming language, we may summarize as, A parent class should be able to replace the child class, And a parent class should be able to refer to the child class objects. The child class may be derived to use all the functions from the parents class. If the child class does the same functions as the parents class, we may say that it is somehow violating the Liskov Substituion Principle.

The Problem Example
Assuming we are have a few micro services that is communicating between themselves. And there is 2 type of micro services. Internal and Public. We are required to send plain text during internal communication and an encrypted text during transmitting to public. We than may practice liskov substitution.

Declare 'Base' Interface
First We declare an interface to define the messaging between the micro services.

Create Internal Message Class
We then may create the first class to handle the first requirement, which is sending internal messages.

Create External Message Class
Then we proceed with the second class,

The Security Helper
From The Previous code snippet, we make use of a security helper, below are the implementation.

The Implementation



Conclusion
From the article, we may see that we make use of all the principle of Liskov.
1. Parent Class Be Replace With Child Class - Interface of IMicromessage
2. Replacing ExternalMessage - with some specific algorithm based on requirement
3. Without Altering The Program - Normal MicroMessage will still able to send message in the MicroHttpService implementation class

Published on : 10-Jan-2019
Ref no : DTC-WPUB-000103

About Author

My photo
Wan Mohd Adzha CAPM,MCPD,MCSD,MCSE
Passionate about new technology ( Software Engineering ) and how to build,manage and maintain them

Comments