Back to Course

Practice · SOLID · LSP · Card 1

Why does this subclass break code that worked with the parent?

A Rectangle. A Square that inherits from it. A test that passes for Rectangle and fails for Square, using only public methods. Why?

The code

A textbook inheritance setup. The Square enforces its own invariant: width == height.

class Rectangle
  attr_accessor :width, :height

  def area
    width * height
  end
end

class Square < Rectangle
  def width=(value)
    super(value)
    @height = value
  end

  def height=(value)
    @width = value
    super(value)
  end
end

# This test passes for Rectangle, fails for Square:
def test_resize(shape)
  shape.width = 3
  shape.height = 5
  assert_equal 15, shape.area
end

The question

Why does the test fail for Square? And what does that tell you about the Square-extends-Rectangle relationship?

Take a moment. The test only uses methods that both classes have. Yet it fails for the subclass. What contract did Square break by overriding the setters?