Should constructors comply with the Liskov Substitution Principle? [closed]

北城余情 提交于 2019-11-28 06:08:14

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.

Definitely No.

Constructors are normally specialized for subtypes. Trying to apply LSP to constructors would be like saying subtypes can't have added specific methods or members. But the restriction is only the other way around.

And I also agree with Philip, constructors are not really part of a type (and in some languages you can easily use other factories instead of constructors). Using smalltalk terminology you would say constructors are methods of meta-classes.

No violation of LSP here, it only applies to instance methods, not to class methods (constructors or any other class methods).

This is sort of an opinionated question but the way I tend to write mine is such that the extra parameters have no real bearing on changing functionality. By that I mean that when my constructor requires an extra parameter in a subclass it is to maintain the standard functionality (but doing different underlying things) this way lets say I create ClassA = new ClassB(with some args); then functionality is the same whether I do this or ClassA = new ClassA(); and I usually use some sort of Factory method to create them so it's seamless in how they work. Again this is just how I do things and is in no way the absolute correct way to do things.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!