里氏替换原则混淆

Liskov Substitution Principle Confusion

我对 LSP 的意图感到困惑。 我正在阅读 Pragmatic Programmer 并且在设计中,通过契约章节,这一行出现在对 LSP 的引用中。

Subclasses 必须可以通过基本 class 界面使用,而无需用户知道差异。

但是,如果我查看其他定义,那么它似乎暗示了完全相反的事实,即实际上应该能够代表基数 class 的 subclass。

有人可以澄清一下吗?

这是表达同一件事的两种方式。

继承是一个被严重滥用的概念,但我相信不搞砸系统设计的最简单方法就是这样考虑:

继承意味着子class 是一个基class。考虑到这一点:

Subclasses must be usable through the base class interface without the need for the user to know the difference.

如果扩展 class,则子class 必须能够替换基 class。脚本必须能够使用 subclass,因为它会使用 base class 而不会失败。

it seems to suggest the exact inverse that in fact it's the subclass that should be able to stand in for the base class.

简单的混淆,意思是一样的。 subclass 必须能够替换 base class.


更多详情:

Subclasses must be usable through the base class interface [...]

基础 class 接口由其契约组成。基础 class 定义了一个 api,通过它可以使用它。例如,基础 class Number 可能具有 public method add(Number $number).

任何扩展 class(例如 Integer)必须能够像任何 Number 一样使用,而无需修改处理数字的代码。