Liskov Substitution Principle [LSP]
A base class should be able to be replaced by its derived class without any change of functionality.
LSP states that a IS-A
relationship is insufficient and should be replaced with IS-SUBSTITUTABLE-FOR
Derived classes should add functionailty rather than remove it.
Type Checking breaks LSP
foreach(var employee in employees) {
if(employee is Manager) { // LSP violation
Helpers.PrintManager(employee as Manager); // LSP violation
break;
}
Helpers.PrintEmployee(employee);
}
Fixing LSP Violations
Use "Tell, Don't Ask"
e.g. in the above sample code, have an employee.Print()
method. This way the employee can decide whether to print as an employee or a manager. (however you are potentially breaking SRP here)
Minimize Null Checks
Use:
- c# nullable reference types
- guard clauses
- Null Object Design Pattern
Follow Interface Segregation Principle
And be sure to fully implement interfaces.