Liskov substitution principle
Line 13: | Line 13: | ||
* Preconditions cannot be strengthened in a subclass. | * Preconditions cannot be strengthened in a subclass. | ||
* Postconditions cannot be weakened in a subclass. | * Postconditions cannot be weakened in a subclass. | ||
+ | |||
+ | Having to check types breaks the [[open closed principle]] | ||
A violation of this principle will occur when a class uses a reference to a base class, but has some knowledge of the subclass(s). | A violation of this principle will occur when a class uses a reference to a base class, but has some knowledge of the subclass(s). |
Revision as of 09:12, 6 October 2008
The Liskov substitution principle (LSP) is a particular definition of subtype that was introduced by Barbara Liskov, in 1987. Succinctly, it states
- Let q(x) be a property provable about objects x of type T. Then q(y) should be true for objects y of type S where S is a subtype of T.
In English, this means that if S is a subclass of T, then any objects of type T in a program can be replaced by object of type S, without changing the correctness of the system. Basically, subclasses should behave exactly like base classes, except with a little extra functionality, but no less.
Or as Robert Martin might say it "every functiona which operates upon a reference or pointer to a base class, should be able to operate upon derivatives of that base class without knowing." Robert Cecil Martin 1996c
This is closely related to Design by contract, which states that
- Preconditions cannot be strengthened in a subclass.
- Postconditions cannot be weakened in a subclass.
Having to check types breaks the open closed principle
A violation of this principle will occur when a class uses a reference to a base class, but has some knowledge of the subclass(s).
A quote to sum it all up
" The Liskov Substitution Principle (A.K.A Design by Contract) is an important feature of all programs that conform to the Open-Closed principle. It is only when derived types are completely substitutable for their base types that functions which use those base types can be reused with impunity, and the derived types can be changed with impunity. " Robert Cecil Martin 1996e