3. Liskov Substitution Principle

Created Friday 15 August 2014

LSP states that Subtypes must be substitutable for their base types

Agile Principles, Patterns, and Practicies in C#

Named for Barbara Liskov, who first described the principle in 1988

If it looks like a duck, quacks like a duck, but needs batteries - you probably have the wrong abstraction

Requirements for LSP to work:

Child classes must not:

LSP suggests that IS-A description for child classes should be replaced with IS-SUBSTITUTABLE-FOR

Invariants

The Problem

LSP Violation "Smells"

foreach (var emp in Employees)
{
if (emp is Manager)
{
_printer.PrintManager(emp as Manager);
}
else
{
_printer.PrintEmployee(emp);
}
}
----------------
public abstract class Base
{
public abstract void Method1();
public abstract void Method2();
}
public class Child : Base
{
public override void Method1()
{
throw new NotImplementedException(); // the smell!
}
public override void Method2()
{
// do stuff
}
}

HINT

Follow ISP
Use small interfaces so you don't require classes to implement more than they need!



Backlinks: