L — From SOLID principles 3/5

Umair Khalid
3 min readAug 19, 2021

Hey Folks,

I hope you guys are writing beautiful code. I’ve something exciting for you this week. I am going to explain the third principle of the SOLID principles series.

If you haven't read my previous two articles on my favorite series, I would highly recommend you guys to go check out Part1 and Part2.

So what is this part named as? “Liskov substitution”

What the hell is this?

Don't worry I got all the basic cover in this article to explain the Liskov substitution principle.

First I would like to state a bookish definition of this principle and then I'll explain it in simple words and write an example for you as well.

Liskov Substitution Principle

This definition seems complex for some of my readers. What if I tell you this principle is also known as Substitutability.

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

In simple words “Objects should be replaceable by their subtypes”. I’ve designed a simple example describing this beautiful principle.

Hold on !! If a Square is extending from Rectange then it should behave like Rectange getArea() will return as different value for a square object and a rectangle object, hence violating the rule without altering the correctness of that program. To resolve this, what we can do is treat them as a different shape

Closely look above example, there is an open class Rectange. I extended Square class from Rectange and we can see it has an “ISA” relation with Rectange type and that makes sense. But hold on!! we have two methods in Rectange class setWidth and setHeight which we are going to to extend and change them in Square class. And if you can notice here problem starts from here when you alter your program to get the correctness. So how do we fix this anti-pattern ?

How do we fix this?

Can you think about any solution ??
No problem I am here to help you out in solving this issue with a well-written solution. Check out my gist.

Now we are on right track as we understood that both of the shapes belong to shape interface but behaviour and attributes of both classes are different so you cant Replace them you program and it will normally, Its mandetory that you will have to modify your program where these classes can be replaced.

I hope you understood this princple and enjoyed my tiny effort to imporve our coding style.

Want to see Source Code for whole serires ?

Thank for reading this article and I appricate your support.

See you in next article :)
Bye bye.

--

--