Wednesday, August 2, 2017

SOLID Principles - Liskov Substitution Principle

The SOLID principles focus on achieving code that is maintainable, robust, and reusable and in this blog, we will discuss the Liskov Substitution Principle.

The derived classes should be perfectly substitutable for their base classes.


Here is an example of Base and derived class:

 Liskov Substitution - Base and Child Class Relation


Rectangle class is base class for Square class and Base class have height, width field and Area function to calculate the area.

public class Rectangle
    {
        public int Height { getprotected set; }
        public int Width  { getprotected set; }

        public virtual void SetWidth(int width)
        {
            Width = width;
        }

        public virtual void SetHeight(int height)
        {
            Height = height;
        }

        public int Area()
        {
            return Width * Height;
        }

    }

    public class Square : Rectangle
    {
        public override void SetHeight(int height)
        {
            Height = height;
            Width = height;
        }

public override void SetWidth(int width)
        {
            Height = width;
            Width = width;
        }

}


Now we will see How the Square Class object will replace the Rectangle base class object, without changing code and can able to calculate the Area of SQUARE by using base class function.

1st example - we instantiate a rectangle object and set height and width of rectangle and call Area () method to get area of rectangle.

Rectangle rect = new Rectangle();
rect.SetHeight(10);
rect.SetWidth(2);
int val = rect.Area(); // Actual value  : 20

2nd example- we are instantiating Square object and assigned to Rectangle object and setting height and width of rectangle and call Area () method to get area of square.

Rectangle rect = new Square();
rect.SetHeight(10);
rect.SetWidth(2);
int val = rect.Area(); // Actual value  : 4


Now in 2nd example, rect holds reference of the type of Square Object, so it’s result is different (area value: 4) and it replace the instance/object of the Rectangle with Square type 

Other Links:


Thanks for Visiting!!

No comments:

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...