SOLID & OOP Principles (50 Qs)•Part 3: Enterprise Architecture, Package Design & Enforcement (25 - 35)
The Circle-Ellipse and Square-Rectangle Dilemma in LSP.
senior LevelCode ExampleSystem Design
In Simple Words:
In mathematics, a Square is a special type of Rectangle ($width = height$).
In Object-Oriented Programming, modeling Square extends Rectangle violates LSP:
typescript
class Rectangle {
setWidth(w: number) { this.width = w; }
setHeight(h: number) { this.height = h; }
}
class Square extends Rectangle {
override setWidth(w: number) { this.width = w; this.height = w; }
override setHeight(h: number) { this.width = h; this.height = h; }
}
- If client code runs:
typescript
rect.setWidth(5); rect.setHeight(10); assert(rect.getArea() === 50); // FAILS for Square (Area is 100)! - Mathematical "is-a" relationships do not equate to behavioral OOP subtyping.