Liskov Substitution

Liskov Substitution Principles Down to Earth

SOLID OOP Wednesday, May 21, 2014

I found it more difficult to understand when I was first introduced to the Liskov substitution principle in its original form. In practical programming, it is much simpler to understand (and explain):


public class LiskovSubstitutionPrincipleDemo
{
  public SomeResult Execute(ISomeInterface dependency)
  {
    return dependency.DoSomeStuff();
  }
}

As Liskov Substitution principles states, the program running does not care what implementation you have in the dependency parameter. It just runs exactly the same way. Of course, different implementations of ISomeInterface would behave differently but that's on the inside. The program executing the execute method doesn't care. It just asks whatever dependency it gets to run the DoSomeStuff method. It always works because it is guaranteed to implement ISomeInterface.

A simplification of a real world example I worked on recently follows:


public class RuleApplier : IRuleApplier
{
  public Outcome Apply(Circumstances circumstances, IRule rule)
  {
    // Whatever the Execute method implementation does is not important for the Apply method.
    // Its job is just to call it.
    return rule.Execute(circumstances);
  }
}