Wednesday, December 16, 2009

Liskov's Substitution Principle

Liskov's Substitution Principle (LSP) is one of the five software design principles. What programming languages you know, you should know these five principles written below :
In this article, i will explain Liskov's Substitution Principle.

LSP is first mentioned by Barbara Liskov in 1987 conference keynote. This principle is about relation between subclasses and base classes. We can say strong behavioral subtyping. When you read the principle, you will find something similar with Open Close Principle.

If function in base class is modified because of that new derivative of the base class is created. You shouldn't need to change function which is placed in base class.

Key Principle
Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.

Violation of Liskov's Substitution Principle
I will write a best known example; Rectangle and Square. You can think of that Square is a kind of  special rectangle. Then the square can be inherited from Rectangle class.

public class Rectangle
{
    protected int _Width;
    protected int _Height;

    public void SetWidth(int width)
    {
        _Width = width;
    }

    public void SetHeight(int height)
    {
        _Height = height;
    }

    public int CalculateArea()
    {
        return _Height * _Width;
    }
}

public class Square : Rectangle
{
    public void SetWidth(int width)
    {
        _Width = width;
        _Height = width;
    }

    public void SetHeight(int height)
    {
        _Height = height;
        _Width = height;
    }
}
public class Program
{
     public static void Main()
     {
        Rectangle r = GetNewRectangle();
        r.SetHeight(5);
        r.SetWidth(10);

        Console.WriteLine(r.CalculateArea()); 
        // Output : 50 instead of 25
     }
     private static Rectangle GetNewRectangle()
     {
        return new Square();
     }
}
The square class which is derived from Rectangle class assumes that width is equal with the height. When Square is used in context where Rectangle class is expected, unexpected behavior may occur, because the dimensions of the square can not be set independently.

For further information you can download pdf file written by Robert C.Martin.