Why specifications?
- Many of the nastiest bugs in programs arise because of misunderstandings about behavior at the interface between two pieces of code
- The contract acts as a firewall between client and implementer
- It shields the client from the details of the workings of the unit.(让用户不必考虑组件的具体工作方式)
- it shields the implementer from the details of the usage of the unit(让实现者不必考虑组件的具体使用情况)
Behavioral equivalence
- The notion of equivalence is in the eye of the beholder — that is, the client
Specification structure
- a precondition, indicated by the keyword requires
- obligation on the client
- a postcondition, indicated by the keyword effects
- obligation on the implementer
- 当前置条件不满足时,程序可以做任何事情,前置条件满足时则后置条件必须被满足
- 当precondition不满足时,扔出一个异常是非常好的处理方式。因为这样可以让程序很快发生异常,让client知道其对该方法的调用出错
Null references
-
DANGER :you’ll get errors at runtime because you can’t call any methods or use any fields with null references
-
null values are implicitly disallowed in parameters and return values
-
e.g :
-
static boolean addAll(@NonNull List<T> list1, @NonNull List<T> list2)
-
What a specification may talk about
- 可以阐述参数、返回值等,不能提到实现中的局部变量等实现的细节,因为函数的使用者可能看不到程序的源代码。
Testing and specifications
- black box and glass box tests must follow the specification
- 测试的输入内容必须符合spec里面的前置条件,不能依据实现细节来测试违反前置条件的测试样例
- 白盒测试指在spec允许的输入中寻找测试所有代码的测试样例,所有的测试样例必须与具体实现无关
Specifications for mutating methods
mutation is disallowed unless stated otherwise
Exceptions
Exceptions的用法:
- signaling bugs
- special results
Checked and unchecked exceptions
- checked exceptions:被编译器静态检查,适合用于special results
- Unchecked exceptions:不被编译器检车,适合用于signaling bugs
Exception design considerations
- unchecked exceptions最好用于处理程序中意想不到的错误,而且这样的错误可以通过客户端代码进行避免。其内容不出现在代码说明(spec)中
- checked exceptions 最好用于可能发生的、客户端代码无法避免的程序异常。通常都出现在代码说明中