[SOLID Principle] Liskov Substitution Principle

R4 Cheng
1 min readAug 23, 2023

--

Subtypes must be substitutable (without breaking the program) for their base (parent) types

Important: OOP focuses on behavior rather than properties

Use Cases

  • Update an algorithm without bothering the user using our interface

Examples

A square should not be a subclass of a rectangle

It might not be intuitive, but it applies to OOP

If we make a square a subclass of a rectangle, we will have to change the code inside the rectangle class to make it work for the square class. This is a violation of the Liskov Substitution Principle.

// declare rectangle class
export class Rectangle {
private height: number;
private width: number;

setHeight(height: number) {
this.height = height;
}

setWidth(width: number) {
this.width = width;
}

getHeight() {
return this.height;
}

getWidth() {
return this.width;
}

getArea() {
return this.height * this.width;
}
}

// violate LSP by extending Rectangle
export class Square extends Rectangle {

setHeight(height: number) {
super.setHeight(height);
super.setWidth(height);
}

setWidth(width: number) {
super.setWidth(width);
super.setHeight(width);
}
}
// TODO: Golang Case

--

--

R4 Cheng
R4 Cheng

Written by R4 Cheng

「0」が過去で「1」が未来「今」は何処にもない

No responses yet