Liskov Substitution Principle

Third SOLID principle is relied to second principle spoken in previous article. This principle concerns to correctly projected earlier inheritance – if derived class is created, there is an urgent need to use derived class instead of base class. Otherwise it means, that inheritance has been wrongly implemented. Simply saying: compatibility of interface and every single method has to be correct in every aspect. Code below shows wrongly implemented inheritance:

abstract class Animal
{
    public abstract void Fly();
    public string Name { get; set; }
   
}

class Bird: Animal
{
    public override void Fly()
    {
        Console.WriteLine("Bird flies");
    }
}

class Fish : Animal
{
    public override void Fly()
    {
        throw new NotImplementedException("Fish can't fly!"); 
    }
}


We have created abstract class called Animal, the most perceptive ones have noticed, that the inheritance mechanism has been wrongly considered. Fish is an animal, but it can’t fly right? And that is our Liskov’s „broken rule”   substitution. The inheritance has to be considered in different way, so the every derived class can use every aspect of base class. In good planned inheritance mechanism, derived class shouldn’t overwrite base classes. They can alternatively expand them by evoking them from base class. Let us consider properly considered example:

class BreweryMachine
{
    public virtual void Brew()
    {
        Console.WriteLine("Pour some water to the tub");
        Console.WriteLine("Insert hop to the tub");
    }
}

class AleBeer: BreweryMachine
{
    public override void Brew()
    {
        base.Brew();
        Console.WriteLine("Brew beer");
    }
}

class Program
{
    static void Main()
    {
        BreweryMachine beer;
        
        Console.WriteLine("Making  an ordinary beer");
        bee r= new BreweryMachine();
        beer.Brew();
        
        Console.WriteLine("Making ale beer");
        beer= new AleBeer();
        beer.Brew();
    }
}

Example shown above precisely restricts Liskov Substitiution principle. You can not only use now object of derived class in base class, but in addition despite using polymorphism, we don’t overwrite methods of base class.