Liskov Substitution Principle

Mochammad Alamsyah
Sep 4, 2018 · 1 min read
Image from Spring Framework Guru

One of principle SOLID Object Design Principles by Bob Martin

“functions that use pointers to base classes must be able to use objects of derived classes without knowing it”.

The classic example of the “is a” technique causing problems is the circle-ellipse problem, but I will show you using my car example

Now, electric car obviously a car, So logically, a sub-class can be created

This violates Liskov Substitution Principle since an electric car is not fueled by litters metrics, but the contract of the Car class states that an electric car can.

This can be solved by applying better domain naming, a Car can be named GasPoweredCar and ElectricPoweredCar. Both classes can be more abstracted by extending from Vehicle base class.

When possible sub-class cannot restrict the freedom of the base class, sub-class should only add extra detail to the domain representation.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade