施工人员是否符合利斯科夫替代原则? [英] Should constructors comply with the Liskov Substitution Principle?

查看:240
本文介绍了施工人员是否符合利斯科夫替代原则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常会尝试确保我的对象实例符合,Liskov替换原则,但我一直想知道是否有人认为LSP也应该应用于构造函数?



我已经尝试谷歌搜索这个,但我还没有找到任何强



我应该注意,我的大部分编码是在Ruby中,但我有时发现我的子类构造函数与父类略有不同。它们采用相同的基本参数集,通常是额外的参数。有时这也会发生在其他类方法。



在我的头后面,这总是感觉像一个LSP违反,但我想看看是否有人感觉这种方式

不,当你使用构造函数时,你知道你正在处理子类型。这允许您具有父构造函数不需要的前提条件,例如其他参数。这是为什么在大多数语言中,构造函数的名字是被创建的类的



这是一个很好的例子,一个 ColoredSquare 可以是 Square 的正确子类型,但需要一个额外的参数: color 。如果你不能做这样的子类型将不太有用。



在某种意义上,构造函数不是类型的一部分:它是一个函数返回该类型的元素。因此,为一个子类型定义一个新的构造函数,不会破坏LSV。


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.

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.

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.

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.

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 LSV.

这篇关于施工人员是否符合利斯科夫替代原则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆