Java Reference
In-Depth Information
author, provided they write the specification before writing the method body. The
act of writing the specification forces the author to be clear and precise; further-
more, the author can then refer to the specification when writing the body.
In conclusion, get in the habit of writing a clear and precise specification for
a method before writing the method, and maintain consistency between specifi-
cation and body.
The form of a specification
A specification of a method may be given in terms of a precondition and a
postcondition . The precondition defines what must be true of the arguments (and
any instance or class variables) when the method is called. The postcondition
defines what will be true of the arguments (and any instance or class variables
and, for a function, the result value) when the method call terminates.
Specification of a procedure
Since a procedure performs some task, write its specification as a command
to do that task. Here are two examples:
Swap b , c , and d so that b≤c≤d .
Print the square of the first n natural numbers.
Deposit d dollars in bank account ba .
Specification of a function
A function produces a value. Therefore, write its spec as an English noun
phrase, mixed with math, which says what that value is. Here are examples:
• = minimum of b and c
• = square root of x , given x≥0
We use = in the specification to say that the value of a call equals the value
that follows = (with parameters of the function replaced by arguments of the
call). Some use the word “return”, as in “return the minimum of b and c ”. This
is all right but not preferred because it is too operational. The user wants to know
only what the value is that the function call provides, so just describe that value.
Specification of a constructor
The purpose of a constructor is to initialize (some of) the fields of a newly
created object of some class. Therefore, the specification of a constructor should
say simply what the initial values of all the fields are. If some of the fields are
given values that depend on the parameters of the constructor, the specification
must name the parameters and say how they are used to initialize the construc-
tor. Here is an example:
/** Constructor: an instance with amplitude a and frequency f */
public Wave( double a, double f)
Search WWH ::

Custom Search