My Simple Understanding of Liskov’s Substitution Principle(No Coding)
Sometimes I ask myself about the SOLID principle about how to use it, why is it made and what is the purpose of this? Well, the answers’ already in the link.
Honestly, I have a hard time understanding the LSP because may be due to its technical definition
Where sometimes I scrambled the words 😩.
So, I tried to get some simple words or ways on my own to understand and to remember this easily :D (Hope this also work for you)
I have these questions in mind to guide me.
- What’s the right keyword for this LSP?
- If you’re struggling in understanding this principle, just remember that the “Substitution” is the keyword. 😉 - When to validate using the LSP?
- This is nice to consider when you’re dealing with an OOP inheritance.
(i.e. Abstract classes)
- If you’re planning on using an existing abstract class or creating one, make sure to validate if this does not violate the LSP.
- If it does violate, here are the options that we can use:
— Use composition over the inheritance if possible.
— Break down its behavior then use an interface (Sometimes I can think of this as a part of the Interface Segregrate Principle of SOLID)
— Remodel your abstract classes by breaking them down if possible - How do I know that I violated the LSP?
— If your child’s class overrides all the parent’s methods. (are you trying to create a different class?)
— If your child’s class overrides a method to throws an exception even one of the parent’s methods. (unless this is the expectations of the base class)
— If your child’s class overrides a method with an empty body. (unless this is the expectations of the base class)
This is a well-known example of violating the Liskov’s Substitution Principle.
Hope this is simple enough for you to proceed on using Liskov’s Substitution Principle, Please let me know in the comment if I missed something, this will help me to understand more about SOLID principles.
Here are my references: with code examples