Sunday, 20 November 2016

Solid Part 3 - LSP (Liskov Substitution Principle)

The third part of SOLID is Liskov Substitution Principle (LSP), a scientific article created by Barbara Liskov in 1987.

The principle says "A base class can be replaced by the derived class". There are two questions to think  about when using the Liskov Principle:
1- Does the base class have useless behaviors for the derived class?
2- Is the external behavior changed when we replace the base class for the derived class?

If one of them is true, using Liskov Principle the relation of the base and derived classes is wrong.

When you are using inheritance if the derived class does not implement all the methods of the base class or part of the methods and attributes of the base class does not make sense for the derived class, according to LSP that inheritance is wrong and may bring future problems to the software. Imagine a software that you have to calculate discounts for new customers and for old customers:

Base CustomerClass
Derived PossibleCustomerClass
Let's see what happens when this code runs:

Console Application
When I run the code above in a Console Application I got the result:

Console Application Running

Oh it works fine, but if I replace Customer for PossibleCustomer?

Possible Customer 

The possible customers can not have a Register Date, when I run that code, I get this result:

PossibleCustomer Error
As we can see, the concept of inheritance can not be used only for reuse the code, the concept must be used only when makes sense the inheritance of characteristics and behaviors of the base class.
In general, when we use Open Closed Principle in our code, is easier to use LSP. 
When we will use inheritance, we must ask "Is the objectA an object of objectB?", for example "Is a dog an animal?" or "Is a chocolate a candy?" if the answer is true and the external behavior of the classes is the same, the derived class can use the behavior and characteristics of the base class.

In some cases, to use LSP we just have to implement the Interface Segregation Principle (ISP), but about that I will write next week!

No comments:

Post a Comment