Lecture 7: Designing Specifications

来源:互联网 发布:域名到期查询 编辑:程序博客网 时间:2024/06/10 23:57

1 deterministic, declarative and strong

  • deterministic
  • declarative: Does the spec just characterize what the output should be, or does it explicitly say how to compute the output?
  • strong: Does the spec have a small set of legal implementations, or a large set?

1.1 Deterministic vs. underdetermined specs

  • Does the spec define only a single possible output for a given input, or allow the implementor to choose from a set of legal outputs?

1.2 Declarative vs. operational specs

  • Almost always, declarative specifications are preferable. They’re usually shorter, easier to understand, and most importantly, they don’t inadvertently expose implementation details that a client may rely on (and then find no longer hold when the implementation is changed).
  • Implementation details should use comments within the body of the method, not in the spec comment.

1.3 Stronger vs. weaker specs

A specification S2 is stronger than or equal to a specification S1 if:

  • S2’s precondition is weaker than or equal to S1’s,
    or
  • S2’s postcondition is stronger than or equal to S1’s, for the states that satisfy S1’s precondition.

2 Designing good specifications

  • The specification should be coherent: shouldn’t have lots of different cases. Long argument lists, deeply nested if-statements, and boolean flags are all signs of trouble.
  • The results of a call should be informative.
  • The specification should be strong enough.(otherwise, hard to trace error)
  • The specification should also be weak enough.(otherwise, hard to achieve)
  • The specification should use abstract types where possible.

3 Precondition or postcondition?

  • The most common use of preconditions is to demand a property precisely because it would be hard or expensive for the method to check it.
  • To determine how to specify precondition or postcondition, the key factors are the cost of the check (in writing and executing code), and the scope of the method. If it’s only called locally in a class, the precondition can be discharged by carefully checking all the sites that call the method. But if the method is public, and used by other developers, it would be less wise to use a precondition. Instead, like the Java API classes, you should throw an exception.

4 About access control

  • Helper methods that are really meant only for local use within the class, and should not be public.

Reference

[1] 6.005 — Software Construction on MIT OpenCourseWare | OCW 6.005 Homepage at https://ocw.mit.edu/ans7870/6/6.005/s16/

0 0
原创粉丝点击