Repaso
Español
Design & PracticesIntermediateDP-03

Square extends Rectangle, and set_width() on a square also changes its height. Code that sets width=2, height=5 and expects area 10 breaks. Which principle is violated?

Options

  1. Single Responsibility
  2. Liskov Substitution (Correct option)
  3. Interface Segregation
  4. Dependency Inversion

Answer

Liskov Substitution

Why

Liskov Substitution says: anywhere the code expects a parent class, you must be able to give it a child class without breaking anything.

Code written for Rectangle assumes width and height change independently. A Square breaks that assumption, so it is not a safe substitute even though 'a square is a rectangle' in math.

Fix: make them separate shapes (or immutable).

Remember

A subclass must keep every promise its parent makes.

Key terms

Practice this question in Repaso