Introduction
In this lesson, we explain abstract superclasses, subtyping, and principle of substitutability (Liskov), design by contracts (Meyer), and the Law of Demeter (Holland, Basili & Lieberherr).
Substitutability is a principle in object-oriented programming stating that, in a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., an object of type T may be substituted with any object of a subtype S) without altering any of the desirable properties of the program (correctness, task performed, etc.). More formally, the Liskov substitution principle (LSP) is a particular definition of a subtyping relation, called (strong) behavioral subtyping, that was initially introduced by Barbara Liskov in a 1987 conference keynote address titled Data Abstraction and Hierarchy. It is a semantic rather than merely syntactic relation, because it intends to guarantee semantic interoperability of types in a hierarchy, object types in particular. Barbara Liskovand Jeannette Wing described the principle succinctly in a 1994 paper as follows:
Subtype Requirement: Let (x) be a property provable about objects x of type T. Then {(y)} should be true for objects y of type S where S is a subtype of T.
The Law of Demeter (LoD) or principle of least knowledge is a design guideline for developing software, particularly object-oriented programs. In its general form, the LoD is a specific case of [loose coupling](https://en.wikipedia.org/wiki/Loose_coupling. The guideline was proposed by Ian Holland at Northeastern University. towards the end of 1987 and extended by Lieberherr and Basili in 1996 as part of Aspect-Oriented Programming (AOP), and can be succinctly summarized in each of the following ways:
- Each unit should have only limited knowledge about other units: only units “closely” related to the current unit.
- Each unit should only talk to its friends; don’t talk to strangers.
- Only talk to your immediate friends.
The fundamental notion is that a given object should assume as little as possible about the structure or properties of anything else (including its subcomponents), in accordance with the principle of “[information hiding](https://en.wikipedia.org/wiki/Information_hiding”. It may be viewed as a corollary to the principle of least privilege, which dictates that a module possess only the information and resources necessary for its legitimate purpose.
LS0tDQp0aXRsZTogIlRoZSBMYXcgb2YgRGVtZXRlciINCnBhcmFtczoNCiAgY2F0ZWdvcnk6IDENCiAgbnVtYmVyOiA4NjgNCiAgdGltZTogIjMwIG1pbiINCiAgbGV2ZWw6IGFkdmFuY2VkDQogIHRhZ3M6IGRlbWV0ZXIsb29wLHByb2dyYW1taW5nDQogIGRlc2NyaXB0aW9uOiAiSW50cm9kdWNlcyB0aGUgT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