Liskov Substitution Principle

The Liskov Substitution Principle

Liskov Substitution Principle

 

We’ve been working our way through the SOLID Principles: We’ve encountered the Single Responsibility Principle (SRP) and the Open-Closed Principle (OCP). Now it’s time to examine the somewhat mysterious Liskov Substitution Principle. It appears that a few developers seem a bit perplexed by the LSP. More so than with the other SOLID Principles. The idea behind the LSP is rather simple. However, it’s formal description is not. Here how Barbara Liskov outlined the principle named after her in 1988:

“What we wanted here is something like the following substitution property: If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behaviour of P is unchanged when o1 is substituted for o2 then S is a subtype of T.” 

More simply:

A program should function the same when we use a subtype instance for a base type reference.

Hmm, still not that clear. 

OK. Let’s get concrete: If class Employee is a Person (i.e. derives from Person), then a program referencing Person should run the same way when we use an instance of Employee. In other words, since an Employee is a Person, it should act like a Person in a program.

Yes, that makes sense.

However, we can easily break this parent-child relationship. Imagine that Person has an Age property. We can ask the Age of a Person instance:

  var age = person.Age;

Say, this doesn’t suit us for Employees. Legislation to prevent age-related discrimination means we are not allowed to display the age of employees anywhere in our programs. 

What if we fixed this in the following manner?

  public override int Age => throw new NotImplementedException();

Can you see the problem?

Unfortunately, we have introduced an LSP violation. If we were to use an Employee in a program that reads a Person’s Age then the program is going to blow up – it will throw an exception. The upshot is that the program will behave radically different for an Employee (a Person) than for a plain-vanilla Person.

What would be a way of resolving this Employee/Person LSP violation?

Hmm, maybe Employee shouldn’t be a Person? Perhaps the interpretation ‘Employee is a Person’ is no longer fully working for us in our programs.

Next time we’ll stay with the LSP and discover other ways in which violations can affect our programs. 

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply