【发布时间】:2017-05-09 19:38:08
【问题描述】:
我正在尝试以正确的方式学习 OOP 和 OOD 原则。我想对 Liskov 替换原则及其 PRE 和 POST 条件进行一些澄清。我在这里阅读了一些主题,来自http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod 和其他地方的一些文章。
我已经编写了一个简单的基类和几个示例子类,其中包含我对其中大部分条件的前置和后置条件的假设,我想知道它们是否正确。 评论行是我的想法:它是否违反了 PRE 和 POST 条件。
public abstract class BaseClass
{
public virtual int GetResult(int x, int y)
{
if (x > 10 && y < 20)
{
return y - x;
}
throw new Exception();
}
}
public class LSPExample1 : BaseClass
{
public override int GetResult(int x, int y)
{
// PRE: weakened pre condition is ok
if (x > 10 && y <= 15)
{
// POST: Is it ok? because the available result range is narrowed by y <= 15
return y - x;
}
throw new Exception();
}
}
public class LSPExample2 : BaseClass
{
public override int GetResult(int x, int y)
{
// PRE: Same as base - OK
if (x > 10 && y < 20)
{
// POST: I assume it's bad because of parameters place changed in substraction ?
return x-y;
}
throw new Exception();
}
}
public class LSPExample3 : BaseClass
{
public override int GetResult(int x, int y)
{
// PRE Condition is bad (Strenghtened) because of (X >5) and (Y>20) ?
if (x > 5 && y > 20)
{
// POST condition is ok because base class do substraction which is weaker than multiplication ?
return x * y;
}
throw new Exception();
}
}
非常感谢您的宝贵时间
【问题讨论】:
标签: oop solid-principles liskov-substitution-principle