Explore Library
Code Quiz

SOLID Principles In Practice

Spot the SOLID violation causing incorrect behavior in a Rectangle/Square hierarchy.

Codetypescript
class Rectangle {
  constructor(protected width: number, protected height: number) {}
  setWidth(w: number) { this.width = w; }
  setHeight(h: number) { this.height = h; }
  area(): number { return this.width * this.height; }
}

class Square extends Rectangle {
  setWidth(w: number) { this.width = w; this.height = w; }
  setHeight(h: number) { this.width = h; this.height = h; }
}

function resizeAndCheck(rect: Rectangle) {
  rect.setWidth(5);
  rect.setHeight(4);
  // Client expects width * height = 20
  console.log(rect.area());
}

resizeAndCheck(new Square(1, 1)); // prints 16, not 20

What SOLID-related bug does this code contain, and how should it be fixed?