Liskovs Substitution Priciple

Liskovs Substitution Priciple can be considered as extension of the Open/Close Principle. It means that new derived classes must extending the base classes without changing their behavior. Sub-types must be consistence to their super-types to avoid incorrect extension of classes. By extending a class for ellipsis to draw a cycle (where length equals height), both parameters must remain within the sub-type.

The principle represents the following code quality Characteristics:

  • Derived types are completeley substitutable for their base types. Functions must be reusable without side-effects. Functions and derived types can be changed with impunity.
  • Classes are defined by “Design by Contract”, where methods declare pre- and post-conditions. Pre-Conditions must be true, otherwise methods are not executed. Upon completion, methods guarantees that its postconditions will be true.
  • “Design by Contract” influences declaration of excetions, such as throws, runtime exceptions and the utilization of try/catch in general.

You can find a short journal about Liskovs Substitution Priciple online.

Example:

A Square violates the the getArea() method of its superclass Rectangle. A solution to this is not deriving Square from Rectangle, or  excluding getArea() from Rectangle.

public class Rectangle {
    private int length;
    private int breadth;

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public int getBreadth() {
        return breadth;
    }

    public void setBreadth(int breadth) {
        this.breadth = breadth;
    }  
 
    public int getArea() {
        return this.length * this.breadth;
    }
}

public class Square extends Rectangle {
    @Override
    public void setBreadth(int breadth) {
        super.setBreadth(breadth);
        super.setLength(breadth);
    }

    @Override
    public void setLength(int length) {
        super.setLength(length);
        super.setBreadth(length);
    }
}