My Simple Understanding of Liskov’s Substitution Principle(No Coding)

June Ligan
3 min readFeb 15, 2021

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

“if class A is a subtype of class B, then we should be able to replace B with A without disrupting the behavior of our program.”
~Baeldung

Where sometimes I scrambled the words 😩.

https://images.app.goo.gl/BWCWHGtZokqLxBiw7

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.

  1. What’s the right keyword for this LSP?
    - If you’re struggling in understanding this principle, just remember that the “Substitution” is the keyword. 😉
  2. 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
  3. 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.

https://images.app.goo.gl/NwQbijN1RGPuq1Tu8

--

--