Java Reference
In-Depth Information
Therefore, a precondition is an important part of the method, and you must document
it. Here we document the precondition that the
amount
parameter must not be
negative.
/**
Deposits money into this account.
@param amount
the amount of money to deposit
(Precondition:
amount >= 0)
*/
Some
javadoc
extensions support a
@precondition
or
@requires
tag, but it
is not a p
art of the standard
javadoc
program. Because the standard
javadoc
tool
skips al
l unknown tags, we simply add the precondition to the method explanation or
the appropriate
@param tag
.
347
348
Preconditions are typically provided for one of two reasons:
1. To restrict the parameters of a method
2. To require that a method is only called when it is in the appropriate state
For example, once a
Scanner
has run out of input, it is no longer legal to call the
next
method. Thus, a precondition for the
next
method is that the
hasNext
method returns
true
.
A method is responsible for operating correctly only when its caller has fulfilled all
preconditions. The method is free to do anything if a precondition is not fulfilled. It
would be perfectly legal if the method reformatted the hard disk every time it was
called with a wrong input. Naturally, that isn't reasonable. What should a method
actually do when it is called with inappropriate inputs? For example, what should
account.deposit(-1000)
do? There are two choices.
1. A method can check for the violation and throw an exception. Then the method
does not return to its caller; instead, control is transferred to an exception
handler. If no handler is present, then the program terminates. We will discuss
exceptions in
Chapter 11
.