Liskov Subtitution Principle

Liskov Subitution principle, easy example

If you find a somewhere a class, which is a base class, you must be able to replace this class with a class that inherits from it.

So in my example on Github we have a invoicing processor. There are types of invoices which inherits from the invoice base class.

public class Invoice
    {}
public class GoodCustomerInvoice : Invoice
    {}

So everywhere where the class: GoodCustomerInvoice is used in the program, it should be possible to replace it with invoice. The program then still should run without errors. That's the basic of the Liskov Subtition Principle

Covariance

The return type of a method in the base class should remain the same in the inherit class. Return types cannot / must not change. Well in C# it's not easy to change the return type in a inherited class. It can be done, when you're using interfaces but it needs effort and it's then violating the Liskov Subtitution Principle. So better not. In my example on Github the invoice is calculating totals and returning the valua as decimal. In every class inheriting from invoice the return type of the calculate totals methods needs to stay decimal.

public virtual decimal GetTotalAmount()
        { }
public override decimal GetTotalAmount()
        { }

ContraVariance

The input type of a method in the base class should remain the same in the inherit class. In my example the invoice class has a method SetInvoiceNumber which takes a int as input type. The principle is saying that you cannot change the int to for instance a decimal in the inheriting class. It must stay an int.

        public virtual void SetInvoiceNumber(int number)
        {
        public override void SetInvoiceNumber(int number)
        {

PreConditions

The principle is saying: don't strenthen the preconditions in the inherit class. In my example there is a method SetInvoiceNumber where the number must be greater then zero but smaller then a million. This condition cannot be changed in the inheriting classes otherwise it violates the principle.

        public virtual void SetInvoiceNumber(int number)
        {
            if(number == 0 || number > 1000.000) throw new ArgumentException(nameof(number));

PostConditions

The postconditions should according to the principle not be weakened.

{{opmerking.Naam}}:

{{opmerking.OpmerkingText}}

            

Saving your comment....

Naam is verplicht!
Email is verplicht!
Opmerking is verplicht!