Decoding SOLID Principles (#3 Liskov Substitution)

Shubhi Puntambekar
2 min readMay 11, 2023

This a continuing series of the SOLID Principles. If you have not gone through the previous thread, I request you to check this post before continuing to read this one.

Liskov Substitution Principle

Just to make you familiar, Barbara Liskov is an American Computer Scientist who has made many contributions to programming languages and distributed computing. Out of many, one of her achievements is the Liskov Substitution principle.

The Liskov Substitution principle states that “Subclasses should be substitutable for their base classes.” What this means is that if class B is a subclass of class A, then we should be able to pass the object of class B to any method that expects an object of class A without disrupting the behaviour of our program.

This might be a little confusing to understand, but let’s break this and understand it with the help of an example.

class Bike:
def turn_on_engine():
pass
def accelerate():
pass

class MotorBike(Bike):
def __init__(self):
self.engineOn = False
self.accelerate = 0

def turn_on_engine():
self.engineOn = True

def accelerate():
if self.engineOn:
self.accelerate += 10


class ElectricBike(Bike):
def turn_on_engine():
raise Exception("No engine found in Electric Bike!")

def accelerate():
# do something to accelerate

If you carefully observe the code, we have implemented the turn_on_engine() function in the ElectricBike class but we are throwing an exception in the function which will break the code. This is changing the behaviour of our base class which in turn is breaking the Liskov Substitution Principle.

Hence, we should avoid such mistakes and make sure that sub-class B should always have all the functionality of parent class A. It can have extra functionality also, but not violate the Liskov Substitution Principle.

Continue reading about the Interface Segregation Principle in the next thread by clicking here.

--

--