Search code examples
liskov-substitution-principle

Liskov substitution principle - overriding method example


Lets say we have this really trivial classes:

class A
{
    virtual int Function(int number)
    {
      return number;
    }
}

class B : A
{
    override int Function(int number)
    {
        return number + 1;
    }
}

class UseExample
{
    void Foo(A obj)
    {
        A.Function(1);
    }
}

Would be this example a violation of the LSP?. If so, could you give me an example that does not break the principle and uses a different implementation?

What about this one:

class B : A
{
    int variable;

    override int Function(int number)
    {
        return number + variable;
    }
}

As far as I understood the use of the variable "variable" causes a stronger pre-condition and therefore it violates the LSP. But i'm not completely sure how to follow the LSP when using Polymorphism.


Solution

  • That's valid, in both cases it doesn't break the principle. B can be substituted for A. It just has different functionality.

    a simple way to break the contract would be to throw an exception in Bs override if the number == 23 or something :)