Why the Liskov Substitution principle?
SOLID
S: Single Responsibility
O: Open-Closed
L: Liskov Substitution
I: Interface Segregation
D: Dependency Inversion
Do you know why SOLID? If not, this read might help you.
Here we will talk about why SOLID. Why we should practice SOLID? How it helps us? How it makes the complex life 🤯 of software developer easy 😌
What is the Liskov Substitution principle?
If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2 then S is a subtype of T
The above animal violates Liskov’s principle because as per above worms are a subtype of animals but worms can’t speak. Hence worms can’t be replaced by Animals. Hence Liskov’s ❌❌
The best way to understand its need is by looking at the results of violating it.
Consider we violate Liskov and go ahead with making worms as animals. The application is expanding we are adding more subtypes of worms to it, and also have added species that do not “eat” to the subtype. Now we have n number of species added to it violating Liskov.
The animal being a parent we have given that contract to other services and now other services think all the animals can speak and eat.
Zoo service is trying to make worm speak, but it cannot because WORM DON’T SPEAK.
Now, what can be the solution to this?
The simplest solution is to add an if statement, if the worm speaks method is called; tell the zoo it can’t speak.
How many “if” condition statements we will add to the code for different species?
Complexing code will create opportunities for all kinds of horrible and mysterious bugs.
Why would any developer want to do complex code?
Why would any developer want to do regression testing to release this complex code to production?
Why would any developer want to spend the weekend fixing bugs?
WHY??
A simple solution to all of these is to just follow Liskov's substitution and have a tight good sleep :P
Refer to this for the Single Responsibility principle, this for Open closed, and follow for ID of SOLID :P
You can follow to stay tuned :)