LSP - Liskov Substitution Principle

Onward to a new principle!

How to create the best inheritance hierarchies? What traps will cause us to create hierarchies that don't conform to OCP? LSP to the rescue :)



LSP is a tough mf!

LSP - Liskov Substitution Principle

Subtypes must be substitutable for their base types.

So... is a Square a Rectangle?

You have been warned!

Rectangle has width and height. Of course in a Square both are equal. If we try to enforce this in Square we are violating Rectangle contract.
Inheritance represents a IS-A relationship between objects. However, this relationship pertains to behaviour so a Square doesn't behave as a Rectangle and, effectively, a Square isn't a Rectangle.
Don't try this at home.



LSP is one of the prime enablers of OCP. The contract of the base type has to be well understood, if not explicitly enforced by the code (TDD can also helps). 

Yes master :)

The term IS-A is too broad to act as a definition of a subtype. The true definition of a subtype is substitutability (does this word even exists? Yes), which is defined by either an explicit or implicit contract.

No comments:

Post a Comment