In this article are going to see what is Liskov Substitution Principle, Objects of the super class can be replaced by objects of the sub classes with out breaking the correctness of the program..
We take one example we take Shape class where we have the Area method which will calculate the area, but when you see the Square which will break the behaviour, if the values are not Equal. the Values of the variable are needs to be Equal for Square
internal abstract class Shape
{
public int Width { get; set; }
public int Height { get; set; }
public abstract int Area();
}
internal class Rectangle : Shape
{
public override int Area()
{
return this.Width * this.Height;
}
}
internal class Square : Shape
{
public override int Area()
{
if(this.Width != this.Height)
throw new InvalidOperationException("All sides
are must be equal for square");
return this.Width * this.Height;
}
}
public class LiskovSubstitutionPrinciple
{
public void CalculateArea()
{
Shape obj1 = new Rectangle();
obj1.Width = 10;
obj1.Height = 20;
obj1.Area();
Shape obj2 = new Square();
obj2.Width = 20;
obj2.Height = 10;
obj2.Area(); // Here Base class behaviour is broken because of exception
}
}
Liskov Substitution Principle
How we make this class to LSP, the Base class behaviour should not broke, so we slightly change the code which adhere to Liskov substitution principle.
internal abstract class Shape
{
public abstract int Area();
}
internal class Square(int SideLength) : Shape
{
public override int Area()
{
return SideLength * SideLength;
}
}
internal class Rectangle(int Width, int Height) : Shape
{
public override int Area()
{
return Width * Height;
}
}
public class LiskovSubstitutionPrinciple
{
public void CalculateArea()
{
List<Shape> shapes = new List<Shape>
{
new Square(7),
new Rectangle(4, 6)
};
foreach (var shape in shapes)
{
Console.WriteLine($"Area of {shape.GetType().Name}: {shape.Area()}");
}
}
}
From the above code you can learn what is Liskov Substitution Principle.