Flavius
Flavius

Reputation: 111

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
    }
}

Upvotes: 0

Views: 224

Answers (2)

Konrad Kokosa
Konrad Kokosa

Reputation: 16878

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.

Upvotes: 2

weston
weston

Reputation: 54781

This is a strengthening of preconditions in the subtype. A clear violation of LSP.

I.e.

Button says:

As long as the button is enabled, on click do some work

ConditionalButton says:

As long as the button is enabled and Condition() is true, on click do some work

Upvotes: 5

Related Questions