简体   繁体   English

`instanceof` 运算符是否违反 Liskov 替换原则?

[英]Does `instanceof` operator violate Liskov Substitution Principle?

For example I have Currency , and Exchange which deals with various implementations of Currency .例如,我有CurrencyExchange ,它处理Currency的各种实现。 I want to have an extra rate for curtain currencies, I do it like so我想对窗帘货币有额外的汇率,我是这样做的

interface Currency { double rate();}
interface Exchange { double convert(Currency currency, double money); }
class PrivateBank implements Exchange {
    @Override
    public double convert(Currency currency, double money) {
        double extra_rate = 1.0;
        if (currency instanceof CanadaDollar) { /// ?
            extra_rate = 1.05;
        }
        return money * currency.rate() * extra_rate;
    }
}

Is LSP violated here?这里是否违反了LSP?

No, because any implementation of Currency can be passed in to convert and a result will be returned.不,因为可以传入Currency的任何实现以进行convert并返回结果。

No. The Liskov Substitution Principle is about subtypes faithfully exhibiting all the properties of their supertypes.不,里氏替换原则是关于子类型忠实地展示其超类型的所有属性。 In no way does it forbid other code from handing different subtypes of the same type differently.它绝不会禁止其他代码以不同的方式处理同一类型的不同子类型。

Your example code is a bit smelly, but not because of any conflict with the LSP.您的示例代码有点臭,但不是因为与 LSP 有任何冲突。

The above is called "potential violation of LSP".以上称为“潜在违反LSP”。 Any instance check to identify the subtype of a Supertype is considered as a potential violation.任何用于识别超类型子类型的实例检查都被视为潜在的违规行为。

The implementation should not differ for different subtypes.不同子类型的实现不应该不同。 In your case there is no conflict other than just a different value.在您的情况下,除了不同的价值外,没有其他冲突。 But still this can be fixed by having a function or value to return exchange rate rather than checking the subtype and setting it.但这仍然可以通过使用 function 或返回汇率的值来解决,而不是检查子类型并进行设置。

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

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