Grokking SOLID Design Principles
Vote

0% completed

Break The Hierarchy for Adhering to LSP

In the previous lesson, ElectricCar extended Car and could not honour refuel(). Now we redesign the hierarchy so that no subclass inherits a promise it cannot keep.

First, Name the Real Mistake

It is tempting to say the mistake was putting ElectricCar under Car. That is part of it. The deeper mistake was the name and meaning of the method.

refuel() describes one way of doing something, which is adding liquid fuel. Only some vehicles do it that way. A base class method should describe the goal that every subclass shares, not the mechanism one subclass happens to use

.....

.....

.....

Like the course? Get enrolled and start learning!
Roman Strijac

Roman Strijac

· 2 years ago

public class ElectricCar : Car {

public override void refuel() {        

    reCharge()

}

private void reCharge() {

    Console.WriteLine("Car is recharging");

}

}

public class ElectricCar : Vehicle {

public override void refuel() {        

    recharge();

}   

private void recharge() {

    Console.WriteLine("Electric car is recharging");

}

}

Show 1 reply
Keshav Garg

Keshav Garg

· 2 years ago

The Liskov Substitution Principle (LSP) is a fundamental principle in object-oriented programming that states that objects of a superclass should be able to be replaced with objects of a subclass without affecting the correctness of the program.

This ensures that the Liskov Substitution Principle is followed: an instance of ElectricCar can replace Car without causing issues.

 We didn't replace superclass object with subclass object in this case. We just replace it with another subclass object?
Show 1 reply

Reading Progress

0%