简体   繁体   English

这是违反《利斯科夫换人原则》的行为吗?

[英]Is this a Liskov Substitution Principle violation?

My custom button is actually a button, so is it violating the LSP? 我的自定义按钮实际上是一个按钮,是否违反了LSP?

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

This is a strengthening of preconditions in the subtype. 这是子类型中前提的加强。 A clear violation of LSP. 明显违反LSP。

Ie

Button says: 按钮说:

As long as the button is enabled, on click do some work 只要启用该按钮,单击时就可以执行一些工作

ConditionalButton says: ConditionalButton说:

As long as the button is enabled and Condition() is true , on click do some work 只要启用了按钮并且Condition()为true ,单击时就可以执行一些工作

In my opinion this does violate LSP. 我认为这确实违反了LSP。 Please refer Object Mentor simplified definition of The Liskov Substitution Principle from Object Mentor article: 请参阅“ 对象导师”文章中“对象导师”的简化定义“ Liskov替代原理”:

“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. 从我们的角度来看,可以将ConditionalButton用作Button似乎没问题。 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 为了使LSP保持并保持“开放-封闭”原则,所有派生类必须符合客户期望的使用它们的基类的行为。

and for sure clients expect that after clicking a button, OnClick will be executed. 并且可以肯定,客户希望单击按钮后将执行OnClick

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. 在我看来, ConditionalButton违反当前形式的LSP,因为Condition允许单击按钮,而与按钮相关的逻辑将不会执行。 If Condition would be related with enabled/disabled flag - it would not violate LSP. 如果Condition将与启用/禁用标志相关-它不会违反LSP。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM