Part 3 of 6 · 2 min read
Square and rectangle
The classic failure.
In school, a square is a rectangle. So it feels natural to write Square extends Rectangle. CA calls this the canonical violation of LSP.
class Rectangle {
protected int w, h;
void setW(int w) { this.w = w; }
void setH(int h) { this.h = h; }
int area() { return w * h; }
}
class Square extends Rectangle {
@Override void setW(int w) { this.w = w; this.h = w; }
@Override void setH(int h) { this.w = h; this.h = h; }
}
A caller written for rectangles does this:
static void test(Rectangle r) {
r.setW(5);
r.setH(2);
System.out.println(r.area());
}
With a Rectangle it prints 10. With a Square, the second call changes both sides to 2, and it prints 4. The caller assumed width and height change on their own. The square cannot keep that promise, because its two sides must move together.
The only way to protect the caller is to add if (r instanceof Square) to it. But then the caller depends on the type, so the types are not substitutable. Every such check also needs to be remembered each time a new subclass appears.
The root cause is that "is a" in geometry means something different from "behaves like" in code. A mutable rectangle has a promise (two independent sides) that a square breaks. The fix is not clever code. The fix is not to inherit.
One valid design drops the shared mutable parent. Make shapes unchanging and give them a common interface that promises only what they all can do.
interface Shape { int area(); }
record Rect(int w, int h) implements Shape { public int area() { return w * h; } }
record Sq(int side) implements Shape { public int area() { return side * side; } }
Now new Rect(5, 2) has an area of 10 and new Sq(3) has 9. No caller can call a setter, so no caller can be surprised.
Substitutable
Two types are substitutable when a caller can use either one through the same interface without knowing which it holds.
Example: Rect and Sq behind Shape, where the caller only asks for the area.
Check yourself:
1. What does the test method print for a Square, and why?
2. What would the caller need to add to survive the square?
3. Why does the Shape design avoid the failure?