Skip to content

Liskov Substitution

There are various explanation of the Liskov substitution principle. For instance, according wikipedia the LSP is: "It is based on the concept of "substitutability" – a principle in object-oriented programming stating that an object (such as a class) may be replaced by a sub-object (such as a class that extends the first class) without breaking the program"

Let's demonstrate it on example of price calculation for bike rental session.

Price for rent a bike?

The CityShare platform offers rental programms which includes various tariffs for the service final rate calculation. The Billing module should not depend on concrete tariff, and a tariff can be substituted by different one at any time.

lsp-example

Tips

When you extend a class, if some of the properties of the initial class are not useful for the new class, the Liskov substitution principle has been violated.

Recommendation

You should always define clear contract (in form of interface) for components used by other part of a system. An interface consumer/client should not depend on concrete implementation, so the system is then flexible and it supports build time or runtime substitution of functionality. There are various types of interfaces on different levels, e.g. Java intarface, Rest API interface, etc.

References