我正在学习关于前置条件以及何时使用它们的相关知识。有人告诉我,前置条件
@pre fileName must be the name of a valid file
以下代码不适用:
/**
Creates a new FileReader, given the name of file to read from.
@param fileName- the name of file to read from
@throw FileNotFoundException - if the named file does not exist,
is a directory rather than a regular file, or for some other reason cannot
be opened for reading.
*/
public FileReader readFile(String fileName) throws FileNotFoundException {
. . .
}//readFile
为什么会这样呢?
编辑:另一个例子
我们假设以下示例已经以“正确”的方式完成。 请注意IllegalArgumentException和前置条件。请注意行为如何得到了很好的定义, 即使设置了前提条件,也声明了throws。最重要的是,请注意它没有包含 NullPointerException的前提条件。再次强调,为什么没有呢?
/**
* @param start the beginning of the period
* @param end the end of the period; must not precede start
* @pre start <= end
* @post The time span of the returned period is positive.
* @throws IllegalArgumentException if start is after end
* @throws NullPointerException if start or end is null
*/
public Period(Date start, Date end) f
这些示例是否避免使用额外的前提条件?有人可能会认为,如果我们避免前提条件,那么为什么还要使用它们呢?也就是说,为什么不用 @throws 声明替换所有的前提条件(如果在这里避免它们的话)?