Java Reference
In-Depth Information
Preconditions and Postconditions
One good way to write a method comment is to break it down into two kinds of
information, called the precondition and the postcondition . The precondition states
what is assumed to be true when the method is called. The method should not be
used and cannot be expected to perform correctly unless the precondition holds. The
postcondition describes the effect of the method call; that is, the postcondition tells
what will be true after the method is executed in a situation in which the precondition
holds. For a method that returns a value, the postcondition describes the value returned
by the method.
The following is an example of a method heading from Display 4.9 with a
precondition and postcondition added:
precondition
postcondition
/**
Precondition: All instance variables of the calling object have
values.
Postcondition: The data in the calling object has been written to
the screen.
*/
public void writeOutput()
You do not need to know the definition of the method writeOutput to use this
method. All that you need to know to use this method is given by the precondition and
postcondition. (The importance of this is more dramatic when the definition of the
method is longer than that of writeOutput .)
When the only postcondition is a description of the value returned, programmers
usually omit the word Postcondition , as in the following example:
/**
Precondition: All instance variables of the calling object have
values.
Returns a string describing the data in the calling object.
*/
public String toString()
Some programmers choose not to use the words precondition and postcondition in
their method comments. However, whether you use the words or not, you should
always think in terms of precondition and postcondition when designing a method and
when deciding what to include in the method comment.
Self-Test Exercises
17. List all the accessor methods in the class DateFifthTry in Display 4.9 .
18. List all the mutator methods in the class DateFifthTry in Display 4.9 .
(continued)
 
Search WWH ::




Custom Search