Skip to main content

Liskov Substitution Principle (LSP)

The Liskov Substitution Principle (LSP) is a principle of object-oriented design that states that objects in a program should be replaceable with instances of their subtypes without affecting the correctness of the program. In other words, if a class is a subtype of another class, then objects of the subtype class should be able to be used wherever objects of the parent class are used without causing any problems. This allows for flexibility and maintainability in object-oriented design, as well as code reusability and extensibility. To implement the LSP, developers can use techniques such as polymorphism and inheritance.

Explain the Liskov Substitution Principle (LSP) like I'm five

The Liskov Substitution Principle is like a game of hide and seek. In hide and seek, there are different types of people who can play, like kids and adults. And even though kids and adults are different, they can still play the same game together. For example, if a kid is hiding, then an adult can still go and find them. And if an adult is hiding, then a kid can still go and find them. So even though kids and adults are different, they can still play hide and seek together without causing any problems. In object-oriented programming, the different types of people are like classes, and the game of hide and seek is like a program. The Liskov Substitution Principle says that objects of different classes should be able to be used together in a program without causing any problems.

Code examples

class Rectangle
attr_accessor :width, :height

def initialize(width, height)
@width = width
@height = height
end

def area
@width * @height
end
end

class Square < Rectangle
def initialize(side_length)
@width = side_length
@height = side_length
end
end

In this code, the Square class is a subclass of the Rectangle class. However, because a square's sides must be equal in length, setting the width and height attributes independently will violate the square's constraints. This means that a Square object cannot be used in the same way as a Rectangle object, violating the Liskov Substitution Principle.