Java Reference
In-Depth Information
13.3
Guidelines for writing methods
This section concerns writing methods so that they are most easily read, under-
stood, and used. Indentation within methods is covered in the previous section.
Comments on declarations of local variables is covered in the next section.
Figure 13.3 contains a complete method. Users of the method, however,
should look only at the specification of the method in order to see what the
method does, and at its header in order to see the result type and the types of the
parameters. This information is used when writing or reading calls to the method.
Here is the spec and header:
/** = smallest of b , c , and d */
public static int smallest ( int b, int c, int d)
13.3.1
The specification as a contract
The specification is a contract between the author of a method and its users. The
author guarantees that the method does what the specification says —no more
and no less— and users rely on that guarantee. It is a logical firewall. On one
side is the method body, which only the author looks at; on the other are the calls
to the method, which only users look at.
Thus, the specification must be consistent with the method body. It must
explain precisely what the method does. If there is any discrepancy between
specification and body, the author has not done their job properly, and users are
forced to waste time trying to understand the method body.
Some think that a specification is not necessary, that one can tell what a
method does from the name and the parameters. But this is a dangerous and
error-prone practice because it is very difficult to pack a complete meaning into
a name. For example, even in the example of Fig. 13.3, without the specification,
some weird person might think that this method would:
Yield 1 if one of the parameters is smaller than the other two and
0 if there is no smallest.
One of the prime beneficiaries of a well-written specification is the method's
/** = smallest of b , c , and d */
public static int smallest ( int b, int c, int d) {
if (b <= c && b <= d)
{ return b; }
if (c <= d)
{ return c; }
return d;
}
Figure 13.3:
An example of a method
Search WWH ::




Custom Search