For questions about the Liskov Substitution Principle (LSP) in object-oriented design, developed by Barbara Liskov and collected by Robert C. Martin as one of the SOLID principles.
Barbara Liskov presented the Liskov Substitution Principle in 1987, as a principle of object-oriented programming. It states that a program should be able to replace an instance of a type with an instance of a subtype, without affecting any desired properties of the program. LSP describes a semantic rather than merely syntactic relation, because it defines behavioral subtypes in excess of functional correctness.
What is wanted here is something like the following substitution property: If for each object
o1
of typeS
there is an objecto2
of typeT
such that for all programsP
defined in terms ofT
, the behavior ofP
is unchanged wheno1
is substituted foro2
thenS
is a subtype ofT
.
For example, suppose we have a class Animal
with a method walk()
, and a subclass Dog
inherits walk()
. In the following snippet, the run-time type of x
is not known.
Animal x;
x = AnimalFactory.createAnimal(some_parameter);
x.walk();
Although Dog.walk()
may override Animal.walk()
, and have a more specific implementation, it should not make a difference to the behavior of the program whether x
is an instance of Animal
or an instance of Dog
.
Robert Martin included the LSP as the third of his solid-principles and has equated it with design-by-contract.
There is a strong relationship between the LSP and the concept of Design by Contract as expounded by Bertrand Meyer. Using this scheme, methods of classes declare preconditions and postconditions. The preconditions must be true in order for the method to execute. Upon completion, the method guarantees that the postcondition will be true.
See the LSP article under Principles of OOD.