Is deriving square from rectangle a violation of Liskov's Substitution Principle?

somaraj picture somaraj · Jun 23, 2009 · Viewed 15.9k times · Source

I am new to design and learning the design principles.

It says deriving square from rectangle is a classic example of violation of Liskov's Substitution Principle.

If that's the case, what should be the correct design?

Answer

Anton Tykhyy picture Anton Tykhyy · Jun 23, 2009

The answer depends on mutability. If your rectangle and square classes are immutable, then Square is really a subtype of Rectangle and it's perfectly OK to derive first from second. Otherwise, Rectangle and Square could both expose an IRectangle with no mutators, but deriving one from the other is wrong since neither type is properly a subtype of the other.