Wednesday, 25 July 2012

The Liskov Substitution Principle

This principle states that :“ Any derived class should be substitutable for their base classes”

Explanation

We must make sure that the new derived classes just extend without replacing the functionality of old classes. Otherwise the new classes can produce undesired effects when they are used in existing program modules.

Likov's Substitution Principle states that if a program module is using a Base class, then the reference to the Base class can be replaced with a Derived class without affecting the functionality of the program module.

How to know its violated?

  • A subclass that does not keep all the external observable behavior of it's parent class
  • A subclass modifies, rather than extends, the external observable behavior of it's parent class.
  • A subclass that throws exceptions in an effort to hide certain behavior defined in it's parent class
  • A subclass that overrides a virtual method defined in it's parent class using an empty implementation in order to hide certain behavior defined in it's parent class

Example

Where it is violated:
Let us say you have a class Rectangle

And say you created a child class Square 


Suppose I am going to calculate Area of a Rectangle 

This application is never going to give me correct out put.
Its always going to show area of a square and not that of the rectangle.

Where it is followed:
 Let us say consider the above example. “SavingsWithDrawform” class has a method which accepts the “Accounts” class object as shown below.
public void WithDraw( Accounts objAcc)
{
//Code Implementation of Account objects
}
The principle of LSP states that it should be legal to pass the the “SavingsAccount” object to the same method, which is as shown
public void WithDraw(SavingsAccounts objAcc)
{
//Passing the derived type should be legal
}

Where to use this?

Ideally you should use it wherever you are going to use a sub-class.
But then,

In the words of Robert Martin, Agile Principles, Patterns and Practices in C# (P.149):

"A good engineer learns when compromise is more profitable than perfection. However, conformance to LSP should not be surrendered lightly. The guarantee that a subclass will always work where its base classes are used is a powerful way to manage complexity. Once it is forsaken, we must consider each subclass individually."


No comments:

Post a Comment