从矩形得出正方形是否违反了Liskov的替代原则? [英] Is deriving square from rectangle a violation of Liskov's Substitution Principle?

查看:191
本文介绍了从矩形得出正方形是否违反了Liskov的替代原则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是设计和学习设计原则的新手。



它表示从矩形获取矩形是违反Liskov替代原则的典型例子。

如果是这样,应该是正确的设计?

解决方案

我相信推理是这样的:



假设你有一个接受矩形并调整其宽度的方法:

  public void SetWidth(Rectangle rect,int width)
{
rect.Width = width;
}

应该是完全合理的,给定一个矩形,假设这个测试将通过:

  Rectangle rect = new Rectangle(50,20); // width,height 

SetWidth(rect,100);

Assert.AreEqual(20,rect.Height);

...因为更改矩形的宽度不会影响其高度。



但是,假设您已经从Rectangle派生了一个新的Square类。根据定义,一个正方形的高度和宽度总是相等的。让我们再试一次:

  Rectangle rect = new Square(20); // width和height 

SetWidth(rect,100);

Assert.AreEqual(20,rect.Height);

该测试将失败,因为将square的宽度设置为100也会更改其高度。 >

因此,通过从Rectangle派生Square来违反Liskov的替代原则。



is-a规则是有意义的真实世界(一个正方形绝对是一种矩形),但并不总是在软件设计领域。



编辑 / p>

为了回答你的问题,正确的设计应该是Rectangle和Square来自一个常见的Polygon或Shape类,它不执行任何关于宽度或高度。


I am new to design and learning the design principles.

It says deriving square from rectangle is a classic example of violation of Liskov's Substitution Principle.

If that's the case, what should be the correct design?

解决方案

I believe the reasoning is something like this:

Let's say you have a method that accepts a rectangle and adjusts its width:

public void SetWidth(Rectangle rect, int width)
{
    rect.Width = width;
}

It should be perfectly reasonable, given what a rectangle is, to assume that this test would pass:

Rectangle rect = new Rectangle(50, 20); // width, height

SetWidth(rect, 100);

Assert.AreEqual(20, rect.Height);

... because changing a rectangle's width does not affect its height.

However, let's say you've derived a new Square class from Rectangle. By definition, a square has height and width always equal. Let's try that test again:

Rectangle rect = new Square(20); // both width and height

SetWidth(rect, 100);

Assert.AreEqual(20, rect.Height);

That test will fail, because setting a square's width to 100 will also change its height.

Thus, Liskov's substitution principle is violated by deriving Square from Rectangle.

The "is-a" rule makes sense in the "real world" (a square is definitely a kind of rectangle), but not always in the world of software design.

Edit

To answer your question, the correct design should probably be that both Rectangle and Square derive from a common "Polygon" or "Shape" class, which does not enforce any rules regarding width or height.

这篇关于从矩形得出正方形是否违反了Liskov的替代原则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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