SOLID Principles in C# – Part 3: Liskov Substitution Principle (LSP)

SOLID Principles in C# – Part 3: Liskov Substitution Principle (LSP)

Introduction

The third SOLID principle is Liskov Substitution Principle (LSP), which states:

"Derived classes should be substitutable for their base classes without altering the correctness of the program."

This means that if a class B is a subclass of class A, then A can be replaced with B without breaking the behavior of the program.

Why LSP is Important?

? Prevents unexpected behavior when using inheritance ? Ensures a reliable and predictable object hierarchy ? Helps maintain clean and reusable code


Bad Example: Violating LSP

Consider a Rectangle class with a derived Square class.

public class Rectangle  
{  
    public virtual int Width { get; set; }  
    public virtual int Height { get; set; }  

    public int GetArea() => Width * Height;  
}  

public class Square : Rectangle  
{  
    public override int Width  
    {  
        set { base.Width = base.Height = value; }  
    }  

    public override int Height  
    {  
        set { base.Width = base.Height = value; }  
    }  
}
        

? Problem: Since a square always has equal width and height, modifying one property changes the other, which breaks the expected behavior of Rectangle. If a function depends on Rectangle, using Square may lead to incorrect results.


Good Example: Following LSP

To follow LSP, avoid inheritance when it alters expected behavior. Instead, use composition.

public interface IShape  
{  
    int GetArea();  
}  

public class Rectangle : IShape  
{  
    public int Width { get; set; }  
    public int Height { get; set; }  

    public int GetArea() => Width * Height;  
}  

public class Square : IShape  
{  
    public int Side { get; set; }  

    public int GetArea() => Side * Side;  
}
        

? Solution: Now, Square and Rectangle implement the same interface (IShape) instead of using inheritance, so they behave independently without breaking the expected functionality.


Conclusion

Liskov Substitution Principle helps ensure that child classes do not alter the behavior of their parent classes. Favor composition over inheritance when a subclass might violate the behavior of its base class.



要查看或添加评论,请登录

Mohamed Sadek的更多文章

社区洞察

其他会员也浏览了