Certainly! Let's dive deeper into the Liskov Substitution Principle (LSP), understand the provided example thoroughly, and then translate it into TypeScript for better clarity.
Understanding the Liskov Substitution Principle (LSP)
Liskov Substitution Principle is one of the five SOLID principles of object-oriented design. It was introduced by Barbara Liskov in 1987 and can be summarized as follows:
"Objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program."
In simpler terms:
- If class
B is a subclass of class A, then an object of class B should behave exactly like an object of class A when used in any context where A is expected.
- The subclass should not introduce behaviors that alter the expected behavior of the superclass.
Analyzing the Rectangle and Square Example
Let's revisit the provided Java example and translate it to TypeScript to illustrate why extending Rectangle with Square violates LSP.
Java Classes
class Rectangle {
protected int width, height;
public Rectangle() {}
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public int getWidth() { return width; }
public void setWidth(int width) { this.width = width; }
public int getHeight() { return height; }
public void setHeight(int height) { this.height = height; }
public int getArea() { return width * height; }
}
class Square extends Rectangle {
public Square() {}
public Square(int size) {
width = height = size;
}
@Override
public void setWidth(int width) {
super.setWidth(width);
super.setHeight(width);
}
@Override
public void setHeight(int height) {
super.setHeight(height);
super.setWidth(height);
}
}
TypeScript Translation
class Rectangle {
protected width: number;
protected height: number;
constructor(width: number = 0, height: number = 0) {
this.width = width;
this.height = height;
}
getWidth(): number {
return this.width;
}
setWidth(width: number): void {
this.width = width;
}
getHeight(): number {
return this.height;
}
setHeight(height: number): void {
this.height = height;
}
getArea(): number {
return this.width * this.height;
}
}
class Square extends Rectangle {
constructor(size: number = 0) {
super(size, size);
}
setWidth(width: number): void {
this.width = width;
this.height = width;
}
setHeight(height: number): void {
this.height = height;
this.width = height;
}
}
The Problem Illustrated
Consider the following TypeScript test function analogous to the Java getAreaTest:
function getAreaTest(rect: Rectangle): void {
const width = rect.getWidth();
rect.setHeight(10);
console.log(`Expected area of ${width * 10}, got ${rect.getArea()}`);
}
function main() {
const rect = new Rectangle(2, 3);
getAreaTest(rect); // Expected: 20, Actual: 20
const sq = new Square(5);
getAreaTest(sq); // Expected: 2 * 10 = 20, Actual: 100
}
main();
Output:
Expected area of 20, got 20
Expected area of 20, got 100
Explanation:
-
Rectangle Test:
- Width: 2
- Height: 3
- After
setHeight(10): Width remains 2, Height becomes 10
- Expected Area: 2 * 10 = 20
- Actual Area: 2 * 10 = 20 ✅
-
Square Test:
- Initial Size: 5 (Width and Height both set to 5)
- After
setHeight(10):
setHeight in Square sets both height and width to 10
- Expected Area: 2 * 10 = 20
- Actual Area: 10 * 10 = 100 ❌
Issue:
- The
Square class overrides setWidth and setHeight to keep width and height equal, maintaining the square's property.
- However, this behavior changes the expectations set by the
Rectangle class. When getAreaTest sets the height explicitly, it doesn't expect the width to change as a side effect.
- This unexpected behavior breaks the Liskov Substitution Principle because substituting a
Square where a Rectangle is expected leads to incorrect behavior.
Why Does Extending Rectangle with Square Violate LSP?
-
Behavioral Contract: The Rectangle class allows width and height to be set independently. The Square, by enforcing that both are equal, alters this behavior.
-
Client Expectations: Clients of Rectangle expect that setting height doesn't affect width. When Square changes this behavior, it violates the client's expectations, potentially leading to bugs.
-
Substitutability: Since Square modifies the behavior of Rectangle in a way that's observable by the client (changing width when height is set), it cannot seamlessly substitute Rectangle without issues.
How to Adhere to LSP in This Scenario
To adhere to LSP, Square should not violate the expectations set by Rectangle. Here are some approaches:
1. Avoid Inheritance for Square and Rectangle
Instead of making Square a subclass of Rectangle, recognize that while mathematically a square is a rectangle, in software design, their behaviors differ when modification is involved.
TypeScript Example:
class Rectangle {
protected width: number;
protected height: number;
constructor(width: number = 0, height: number = 0) {
this.width = width;
this.height = height;
}
getWidth(): number { return this.width; }
setWidth(width: number): void { this.width = width; }
getHeight(): number { return this.height; }
setHeight(height: number): void { this.height = height; }
getArea(): number { return this.width * this.height; }
}
class Square {
private size: number;
constructor(size: number = 0) {
this.size = size;
}
getSize(): number { return this.size; }
setSize(size: number): void { this.size = size; }
getArea(): number { return this.size * this.size; }
}
// Adjust the test function to accept both Rectangle and Square without inheritance
function getAreaTest(obj: { getArea: () => number }): void {
console.log(`Area is ${obj.getArea()}`);
}
Pros:
- Clear separation of behaviors.
- Avoids unintended side effects.
Cons:
- Lose the benefits of polymorphism through inheritance.
2. Use Composition Over Inheritance
Instead of having Square inherit from Rectangle, have Square contain a Rectangle instance.
TypeScript Example:
class Rectangle {
protected width: number;
protected height: number;
constructor(width: number = 0, height: number = 0) {
this.width = width;
this.height = height;
}
getWidth(): number { return this.width; }
setWidth(width: number): void { this.width = width; }
getHeight(): number { return this.height; }
setHeight(height: number): void { this.height = height; }
getArea(): number { return this.width * this.height; }
}
class Square {
private rectangle: Rectangle;
constructor(size: number = 0) {
this.rectangle = new Rectangle(size, size);
}
getSize(): number { return this.rectangle.getWidth(); }
setSize(size: number): void {
this.rectangle.setWidth(size);
this.rectangle.setHeight(size);
}
getArea(): number { return this.rectangle.getArea(); }
}
Pros:
- Maintains the distinct behavior of
Square and Rectangle.
- Promotes code reuse through composition.
Cons:
- Slightly more complex structure.
3. Define a Common Interface That Enforces Correct Behavior
Create an interface that both Rectangle and Square adhere to, ensuring they implement methods consistently without forcing wrong inheritance.
TypeScript Example:
interface Shape {
getArea(): number;
}
class Rectangle implements Shape {
protected width: number;
protected height: number;
constructor(width: number = 0, height: number = 0) {
this.width = width;
this.height = height;
}
getWidth(): number { return this.width; }
setWidth(width: number): void { this.width = width; }
getHeight(): number { return this.height; }
setHeight(height: number): void { this.height = height; }
getArea(): number { return this.width * this.height; }
}
class Square implements Shape {
private size: number;
constructor(size: number = 0) {
this.size = size;
}
getSize(): number { return this.size; }
setSize(size: number): void { this.size = size; }
getArea(): number { return this.size * this.size; }
}
// Now, the test function works with any Shape
function getAreaTest(shape: Shape): void {
console.log(`Area is ${shape.getArea()}`);
}
Pros:
- Adheres to LSP by ensuring consistent behavior through the
Shape interface.
- Flexible and promotes polymorphism without unsafe inheritance.
Cons:
- Less specific; may require additional methods/interfaces for more complex scenarios.
Key Takeaways
-
Inheritance vs. Composition:
- Inheritance implies an "is-a" relationship, but it should not introduce behaviors that violate the parent's contract.
- Composition promotes flexibility by building complex behaviors from simpler components without forcing inappropriate relationships.
-
Designing with LSP in Mind:
- Always ensure that subclasses can stand in for their superclasses without altering the expected behavior.
- Be cautious when forcing inheritance hierarchies; ensure that they truly represent substitutable types.
-
Using Interfaces:
- Leveraging interfaces (or abstract classes) can help define contracts that multiple classes adhere to without enforcing inappropriate inheritance.
-
Testing for LSP:
- Implement tests that substitute subclasses in place of superclasses to ensure behavior remains consistent.
- Automated tests can help detect violations of LSP early in the development process.
By understanding and applying the Liskov Substitution Principle, you can design more robust, maintainable, and flexible object-oriented systems. Translating examples into familiar languages like TypeScript can further solidify these concepts and reveal potential design pitfalls.