Liskov substitution principle (LSP)

This is the “L” in SOLID.

LSP suggests that IS-A relationships between classes should be replaced with IS-SUBSTITUTABLE-FOR

Definition

“The Liskov Substitution Principle states that Subtypes must be substitutable for their base types.”

  • Named for Barbara Liskov, who first described the principle in 1988.

In order for substitutability to work child classes must not:

  • Remove base class behavior
  • Violate base class invariants, these could be any constraints defined (or reasonable assumed by clients) on the base classes.

Why follow LSP?

If the classes are none substitutable then polymorphism will not work and there will be code smells added such as if conditions / switches which will be hard to maintain. This also violates the Open / Closed Principle (OCP)

You will also have issues such as NotImplementedException(); being left in inherited methods. This violates the Interface Segregation Principle (ISP)

References

Leave a Reply