Pages

Saturday, December 22, 2018

SOLID - Liskov Substitution Principle

If S is a subtype of T, then objects of type T can be substituted by objects of type S without breaking the program.

public class Employee {
    public string Firstname {get; set;}
    public string Lastname { get; set;}

    public virtual void AssignManager (Employee Manager)
    {
          // set manager for employee
    }
}


Employee emp = new Employee();
emp.AssignManager();


Above, Employee type is T.


public class Staff : Employee {
    public string Dept {get; set;}
    public string Manager {get; set;}
}

Above, Staff (S) is a subtype of T (Employee). Liskov says that since S is a subtype of T, then this should work:


Employee emp = new Staff();
emp.AssignManager();


Let's create another subtype of Employee (T).

public class CEO : Employee{
       public string Rating {get; set;}
       public override void AssignManager(Employee manager)
       {
               throw new Exception("CEO does not have a manager");
       }
}


Above, CEO is subtype of Employee. However, this does not work and thus, it violates the Liskov Principle:

Employee emp = new CEO();
emp.AssignManager();

This code throws an exception because 1) CEO does not have a manager  2) code is set to throw error for invalid method.

Liskov Sub Principle states that Staff() should be a TRUE Employee().
CEO should be a TRUE Employee(), but it is not. So LSP is violated.

How to fix so that even CEO (subtype object of T) can be substituted for the objects of T? So that above code works?

No comments:

Post a Comment