What is an example of the Liskov Substitution Principle?
definition, design-principles, liskov-substitution-principle, oop, solid-principles
Solution
A great example illustrating LSP (given by Uncle Bob in a podcast I heard recently) was how sometimes something that sounds right in natural language doesn't quite work in code.
In mathematics, a `Square` is a `Rectangle`. Indeed it is a specialization of a rectangle. The "is a" makes you want to model this with inheritance. However if in code you made `Square` derive from `Rectangle`, then a `Square` should be usable anywhere you expect a `Rectangle`. This makes for some strange behavior.
Imagine you had `SetWidth` and `SetHeight` methods on your `Rectangle` base class; this seems perfectly logical. However if your `Rectangle` reference pointed to a `Square`, then `SetWidth` and `SetHeight` doesn't make sense because setting one would change the other to match it. In this case `Square` fails the Liskov Substitution Test with `Rectangle` and the abstraction of having `Square` inherit from `Rectangle` is a bad one.
Y'all should check out the other priceless SOLID Principles Explained With Motivational Posters.
Problem
I have heard that the Liskov Substitution Principle (LSP) is a fundamental principle of object oriented design. What is it and what are some examples of its use?
Related problems
- What are the differences between functions and methods in Swift?
- The type system in Scala is Turing complete. Proof? Example? Benefits?
- What is the difference between covariance and contra-variance in programming languages?
- What is an invariant?
- Can anyone provide an example of the Liskov Substitution Principle (LSP) using Vehicles?
- Why avoid subtyping?
- How to implement SOLID principles into an existing project
- What is Turing Complete?