202204291513 Liskov substitution
The Liskov substitution principle of the 202204272244 SOLID design principles for software development, which states:
Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.1
In more formal terms, the Liskov substitution principle is a subtyping relation called strong behavioral subtyping. It imposes contravariance on parameters, covariance on return types, as well as behavioral constraints on the subtype such as:
- It cannot throw new types of exceptions that the base class doesn't unless they are subtypes of the exceptions that the base class throws
- Preconditions cannot be strengthened
- Postconditions cannot be weakened
- Invariants cannot be weakened
- Extending the subtype to allow changes in state that are not permissible to the base class. E.g., a
Pointbase class that does not allow modifying the coordinates after creation should not be extended asMutablePointwhich does. The substitution of these two objects (and other sibling subtypes ofPoint) would not be transparent anymore. This does not apply to fields and methods added solely by the sub-class.
This principle is formulated in an object oriented programming paradigm, but is not restricted to it. These concepts of subtyping and substitution are applicable anywhere that programs have types — even in dynamic languages without a "type system" per se, a function still has a signature, an object still has state, methods, and a public interface, etc.
-
Wikipedia contributors. (2022). SOLID. In Wikipedia. https://en.wikipedia.org/w/index.php?title=SOLID&oldid=1069309351 ↩