Wiki says:
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 T (correctness, task performed, etc.).
My understanding from this,
If T
is an abstraction that provides encapsulation to protect invariants of state maintained by instances of T
, then S
is an abstraction that MUST at-least provide encapsulation to protect same invariants of those inherited states maintained by instances of S
.
Here abstraction can not not only be a class but also a function. For example: function written in prototypical paradigm(ES5 JavaScript)
A class(T
or S
) knows, the contracts their instances should obey.
LSP is about S
ensuring encapsulation to protect invariant of state, that gets inherited from T
. My understanding is, correctness is about protecting invariants to maintain correctness of state.
Is that the right understanding?
IList
interface, which has contracts such as theAdd
method. The framework also contains types that implement that interface, but throw theNotImplementedException
whenAdd
is called. As such, those types can be said to break the LSP.