SOLID Principles: Liskov Substitution Principle


Liskov Substitution Principle, or LSP, is actually a very simple concept to understand in a strongly typed language. In languages like C#, or VB.NET, LSP often gets taken for granted, but I’ve seen cases where even in strongly typed languages you can violate LSP.

Simply put, LSP means that for a given base class, you should be able to substitute derived classes in it’s place, and the behavior or the expectation of that behavior should not change. Take for example a Shape:

public abstract class Shape
{
abstract double GetArea();
}
view raw Shape.cs This Gist brought to you by GitHub.

The point of this class is to define something which has the ability to give us it’s area back. Something like a Square

public class Square : Shape
{
public Square(int side)
{
Side = side;
}

private int Side { get; set; }

public override double GetArea()
{
return Side * Side;
}
}

view raw Square.cs This Gist brought to you by GitHub.

or a Circle

public class Circle : Shape
{
public Circle(int radius)
{
Radius = radius;
}

private int Radius { get; set; }

public override double GetArea()
{
var area = 4 * Math.Pi * Radius * Radius;
return ;
}
}
view raw Circle.cs This Gist brought to you by GitHub.

would have the means to give us this information.

However, something like a Line

public class Line : Shape
{
public Line(int length)
{
Length = length;
}

private int Length { get; set; }

public override double GetArea()
{
throw new NotSupportedException(
@"I'm not really a shape!");
}
}
view raw Line.cs This Gist brought to you by GitHub.

would not be able to give us it’s area, because it doesn’t have an area. In fact, it’s not even a Shape to begin with. It seems odd that I would use this as an example, but the simplicity of the example shows exactly how LSP gets violated in practice. All too often I’ll see code where a class is deriving from another class, even though it’s shouldn’t be. At the core of the issue is usually that it was never meant to be the thing it was deriving from in the first place.

A full running example of utilizing LSP can be found on this video from dime casts.



1 Comment

  1. Great post. As a learner its good start to add skills. Thanks Joseph for this post