Liskov Substitution Principle (LSP)

Intent

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

Description

The users of a base class should function properly if a derivative of that base class is passed to it.

Consider a widget hierarchy as follows. All the derived widgets implement the operations defined in the base Widget class.

widget hierarchy

Now consider a getCaption() function which takes Widget class reference (or pointer) and operates on it.

Dialog.cs

class Dialog
{
void getCaption(Widget widget)
{
string str = widget.getText();

//do something with the string
}
}

The Widget class has Button and Edit controls as its derivatives and the getCaption() function will execute smoothly. But once we add ListBox in the hierarchy, it necessitates the addition of getTextArray() method because a ListBox can have multiple selected items. Now the getCaption() function has to be updated as it has to deal with ListBox control differently as shown in the code. This violates the Liskov Substitution Principle.

Dialog.cs

class Dialog
{
void getCaption(Widget widget)
{
if(widget is ListBox)
{
ListBox listbox = (ListBox)widget;
string str = listbox.getText();
string[] selectedItems = listbox.GetSelectedItems();

//do something with the string
}
else
{
//rest of the code for other widgets
}
}
}

Now getCaption() has to know about the derivatives of the Widget class in order to deal with them. This function will also violate Open-Closed Principle as each time we add an additional class to the hierarchy that needs to be treated differently, getCaption() function will have to be changed again. The hierarchy thus violates “is a” principle of inheritance.

Refactored Solution

In this case, the solution may be to use the widget sub classes directly and not rely on Liskov Substitution Principle. Lot of widgets will have variations in their methods and properties which would be difficult to represent through the Widget class. Trying to fit everything in the Widget class will make it overly complicated. You can see Interface Segregation Principle (ISP) as the next post. Stay tuned with us.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s