Liskov Substitution Priniciple

 Just some few points to get back to , since for some reason I keep on forgetting what its intention out of the 5 SOLID principles.

Historical intro: 
As per wikipedia it was introduced by Barbara Liskov  in a 1988 conference keynote that was titled Data abstraction and hierarchy.

It was defined as:

"Let {\displaystyle \phi (x)} Ø(xbe a property provable about objects {\displaystyle x}(x) of type T. Then {\displaystyle \phi (y)} Ø(y) should be true for objects {\displaystyle y} (y)  of type S where S is a subtype of T."

So to simplify it a little bit , x here is like an instance or an object of class of type T, this could be a User , Class or Employee Class,...etc.

Same Also goes for (y) , it can be an instance of a class of type S.

so what Liskov principal states here is that if a certain property/method  (Ø(x)) do exists in objects of type

T, then this exact same property/method has to be presented in objects of type (S) as well,  if  S is a subtype of T.

In Other words: we should be able to  replace objects of a parent class with objects of subclass without breaking the application.

I believe this is trying to make us think before using Inheritance , as in order not to break the Liskov Principle we need to make sure that all of the sub-classes have all the existing functionalities of their  parent class. So what usually happens is that we start with a general type and then as requirements change/become more clearer/ time pass we need to add some special cases , but what Liskov principle trying to tell us is to maintain the properties of the Parent general class with the more specific case , or should we do it in a different way altogether other than inheritance (an (is-a) relation), by using composition (a (has-a ) relation )for example which is BTW more flexible and less troublesome .  


I believe the most famous example is the Rectangle and Square ,where the rectangle is the Parent class while the square is the sub-class but if we are to use them interchangeably then the fact that a rectangle has his own width and height change independently of one another would be violated by the fact that a Square has his width and height set to the same value.


Some more examples can be found here :
Satckoverflow-Examples on Liskov Principle 

Comments

Popular posts from this blog

Head First Architecture

Head First Architecture Chapter-3

The Culture Map -Some notes