Search code examples
c#oopsolid-principles

Is this a Liskov Substitution Principle violation?


My custom button is actually a button, so is it violating the LSP?

class ConditionalButton : Button
{
    protected override void OnClick(EventArgs e)
    {
        if (Condition())
            base.OnClick(e);
    }
    private bool Condition()
    {
        //return true or false
    }
}

Solution

  • In my opinion this does violate LSP. Please refer Object Mentor simplified definition of The Liskov Substitution Principle from Object Mentor article:

    “Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.”

    It would seem it is ok as we can use ConditionalButton as a Button from this point of view. But:

    In order for the LSP to hold, and with it the Open-Closed principle, all derivatives must conform to the behavior that clients expect of the base classes that they use

    and for sure clients expect that after clicking a button, OnClick will be executed.

    Moreover, from the same article:

    ...when redefining a routine [in a derivative], you may only replace its precondition by a weaker one, and its postcondition by a stronger one.

    In my opinion, ConditionalButton Violates LSP in current form, because Condition allows to click a button, while logic related with button won't be executed. If Condition would be related with enabled/disabled flag - it would not violate LSP.