Created Tuesday 15 October 2013
- http://stackoverflow.com/questions/56860/what-is-the-liskov-substitution-principle
- Bob Martin: http://www.objectmentor.com/resources/articles/lsp.pdf
See also DesignByContract.
- The LSP is functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.
Some rules of thumb to help ensure LSP:
- Whenever possible, avoid overriding concrete methods.
- If you do, see if you can call the method you are overriding in the overriding method.
Related to LSP is NormalizedHierarchy
Example: Circle-Ellipse Problem
A circle is a special case of an ellipse, so should we use inheritance to model this relationship?
Probably not. While a circle is an ellipse, the Circle Object behaves differently than the Ellipse Object.
Suppose the ellipse class looks like this:
class Ellipse { //bunch of math constants int centerX, centerY; int h, k; int a, b; public void stretchX(float s) { //stretch the ellipse horizontally } }
- If you override #stretchX to stretch horizontally and vertically, this breaks LSP. (If you call #stretchX on an ellipse, then you don't expect it to also stretch vertically. Why is this a big deal? Imagine the ellipse lived in a rectangle on the screen. If #stretchX behaved this way, the ellipse might pop out of the rectangle...an unexpected result.)
- If you don't override #stretchX on a circle and call #stretchX on a circle, then it won't be a circle anymore. (This breaks the Circle object.)