问题描述
我通常会尝试确保我的对象实例符合 Liskov Substitution Principle,但我一直想知道人们是否认为 LSP 也应该适用于构造函数?
I usually try to make sure my object instances comply with the Liskov Substitution Principle, but I've always wondered is do people think LSP should apply to constructors too?
我试过在谷歌上搜索这个,但无论如何我都找不到任何强烈的意见.
I've tried googling for this but I haven't been able to find any strong opinions either way.
我应该注意到我的大部分编码都是用 Ruby 编写的,但我有时会发现我的子类构造函数与父类略有不同.它们采用相同的基本参数集,通常还有额外的参数.有时,其他类方法也会发生这种情况.
I should note that most of my coding is in Ruby, but I sometimes find that my subclass constructors are slightly different from the parent class. They take the same base set of arguments, and often extra args. Sometimes this also happens with other class methods.
在我的脑海里,这一直感觉像是违反了 LSP,但我想看看其他人是否也有这种感觉.
In the back of my head this has always felt like an LSP violation, but I wanted to see if anyone else feels this way too.
推荐答案
不,当您使用构造函数时,您知道您正在处理子类型.这允许您拥有父构造函数不需要的先决条件,例如其他参数.这就是为什么在大多数语言中构造函数的名称是所创建的类的名称.
No, when you use a constructor you know you are dealing with the subtype. This allows you to have preconditions not required for the parent constructor such as other parameters. This is why in most languages the constructor name is that of the class being created.
一个很好的例子是 ColoredSquare
可以是 Square
的正确子类型,但需要一个额外的参数:color
.如果你不能做这样的事情,子类型就没那么有用了.
A good example of how this is that a ColoredSquare
could be a proper subtype of Square
, but requires an extra parameter: color
. If you couldn't do things like this subtypes would be much less useful.
从某种意义上说,构造函数实际上并不是类型的一部分:它是一个返回该类型元素的函数.因此,为子类型定义新的构造函数不会破坏 LSP.
In some sense, the constructor isn't really part of the type: it is a function that returns an element of that type. Thus, defining a new constructor for a subtype, doesn't break LSP.
这篇关于构造函数是否应该遵守 Liskov 替换原则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!