前提条件可以表示(用于验证)为简单条件吗?



我理解,在契约/Liskov原则的Desing上下文中,前提条件是在调用代码之前应该为真的东西,例如调用者对此负责。此外,埃菲尔铁塔语言的作者表示,大多数人确实在所谓的cade中放置了另一个验证检查,只是作为防御性编程的手段。

Some time ago I read a question with a code similar to this:
void X(int value)
{
if (value > 100)
{do something...}
}

一些评论者认为 if 语句不是先决条件,但我认为这是不对的 - 如果合约声明 V 必须是 100,那么这是在进一步验证前提条件,如果一个类是从这种类型派生的并且更改为 v> 200,它将加强前提条件,从而违反 Liskov 原则。或者不是这样吗?

正如您所说,前提条件被定义为在执行后续代码之前必须始终为真的条件。

这意味着,在执行其他代码之前在函数开头检查条件的任何内容都被视为前提条件。

例:

//We will do something cool here
//With an integer input
int doSomethingCool(final int input)
{
//Wait, what if input is null or less than 100?
if(null == input || input < 100)
{
//Return a -1 to signify an issue
return -1;    
}
//The cool bit of multiplying by 50. So cool.
final int results = input * 50;
//Return the results;
return results;
}

在此示例中,函数input在执行任何其他操作之前被检查。只要满足条件,那么其余代码就会执行。

不好的例子:

//We will do something cool here
//With an integer input
int doSomethingCool(final int input)
{
//Want to make sure input is not null and larger than 100
if(null != input && input > 100)
{
//The cool bit of multiplying by 50. So cool.
final int results = input * 50;
//Return the results;
return results;
}
//Return a -1 to signify an issue because the
//preconditions were not met for some reason
return -1;
}

在该示例中,前提是检查input是否null且大于 100。这是一个不好的先决条件,因为它可能会引入不必要的if嵌套和循环。

前提条件应执行检查,并且仅在检查失败时才返回。在前提条件下不应该做任何工作。

根据 Liskov 替换原理,如果类型S是类型T的子类型,则类型T可以替换为类型S。如果类型S覆盖doSomethingCool并更改前提条件,则它违反了,因为类型T是基本定义,并定义了必须满足的预期条件。

现在给你答案

是的,简单条件仍然算作先决条件。只要它们位于使用该变量的所有其他代码的前面,条件就是程序所需的条件。此外,如果函数位于子类型中并且重写了父类,则它不应更改前提条件。

但是,不要将需要在前提条件内运行的代码括起来。这是不好的做法。如果value需要大于 100,请检查value < 100并在if检查中设置退货。

最新更新