LSP讨论 [英] LSP discussion

查看:148
本文介绍了LSP讨论的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很好的文章,但LSP实际上代表什么?

Nice article but what does LSP actually stand for?

推荐答案

@Banfa


我多么愚蠢: Liskov替换原则。


亲切的问候,


Jos
@Banfa
How silly of me: "Liskov Substitution Principle".

kind regards,

Jos


我有没有想过它是否编译。我可以看到行
I ever wonder if it compiles. I can see line

public void setWidth(double width){this.setSide(side);你的代码中有
public void setWidth(double width) { this.setSide(side); }



,但是我看不到变量side的任何定义。我不知道为什么宽度没用过。


也许你打算写:

in your code, but I can''t see any definition of variable "side" and I don''t know why "width" isn''t used.

Maybe you intended to write:

< span class =codeLinkonclick =Blur(this,this.parentNode.parentNode,getChildren(this),true);>展开 | 选择 | Wrap | 行号


直观地说,我会给出一个更简单的解释:

case a)如果调用Rectangle.setWidth(x),则执行Rectangle类中的方法setWidth()。

case b)如果调用Square.setWidth(x),则执行Square类中的方法setWidth()。


如果a),如果你只调用

Rectangle.setWidth(x)没有调用Rectangle.setHeight(),那么高度就是你ndefined并保持为0.因此稍后调用getArea()始终返回x * 0 = 0。

如果是b),如果调用Square.setWidth(x),则调用Rectangle.setWidth(x)和Rectangle.setHeight(x)。因此,稍后调用getArea()始终返回x * x。


这对我来说似乎是正确的行为。 Rectangle类的实现是不正确的:一个优秀的程序员应该始终关心他的所有变量都是明确定义的。这意味着,如果调用getArea(),则应测试之前是否调用了两个方法setWidth()和setHeight(),并抛出异常:错误:高度/宽度未定义否则。


一个更好的设计,使一个更加用户友好的方法,不会抛出异常,只提供一种方法:
Intuitively, I would have given an easier explanation:
case a) If you call Rectangle.setWidth(x), then the method setWidth() from the Rectangle class is executed.
case b) If you call Square.setWidth(x), then the method setWidth() from the Square class is executed.

In case a), if you only call
Rectangle.setWidth(x) without calling Rectangle.setHeight(), then the height is undefined and remains 0. So calling getArea() later on always returns x*0 =0.
In case b), if you call Square.setWidth(x), then Rectangle.setWidth(x) and Rectangle.setHeight(x) are both called. So calling getArea() later on always returns x*x.

That seems a correct behaviour for me. Incorrect is the implementation of the Rectangle class: a good programmer should always care that all his variables are well defined. That means, if you call getArea(), you should test if both methods setWidth() and setHeight() are called before, and throw an Exception: "Error: height/width is not defined" otherwise.

A much better design to make a more user-friendly method that doesn''t throw an exception, is to provide only one method:
展开 | 选择 | Wrap | 行号


这篇关于LSP讨论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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