L — What is that Liskov Substitution Principle

Tuba Saday
What is that  ‘SOLID’?
2 min readOct 16, 2021
Liskov’un yerine koyma prensibini en iyi açıklama şekli bu görsel olabilir sanırım :)

There are so many similarities between cats, tigers and lions when we think about it, they are all from cats breed, they, can hunt, have same dna and anatomy each others. According to Liskov, we should be able to expect a tiger to be a cat and a cat to behave like a tiger without having to make any changes.

The Liskov substitution principle was introduced by Barbara Liskov at the 1987 “Data abstraction” conference. Then, Robert Martin edited this principle and introduced it in SOLID in his own article.

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. — Barbara Liskov.

Instead of the explanation similar to the Cybertronian language we’ve written above, we can use the simplified explanation below.

Subtypes must be substitutable for base types. — Barbara Liskov.

According to Simple Object-Oriented Design, the relationship between elements can be in two ways.;

  • One X element can be one XP element. (Something IS-A something else)

An eagle is a bird. — IS-A relation.

  • One Y element can have an XP element. (Something HAS-A property)

An address has a city. — HAS-A relation.

According to LSP;

The IS-A relationship is not sufficient for a good design, such relationships should be replaced with a substitute-relation (IS-SUBSTITUABLE-FOR). So this means that an X element should be able to replace with its base element, or with a Y element that inherited its base element.

We can understand and solve that a design does not comply with LSP as follows;

  • When we check the type of any variable in our code.

The fixed version:

  • When we check whether a property in the element we inherit is empty.

The fixed version:

  • Every time we get NotImplementedException.

The fixed version:

If we comply with the LSP, we can explain the benefits of the term ‘substitution’, as follows;

Thus, in HuntingShow, regardless of its type (cat, tiger), every class derived from the ICanHuntable interface will behave the same and will not cause any corruption.

--

--

Tuba Saday
What is that  ‘SOLID’?

It’s a non stoppable learner and an insane developer.