In Lesson 4, we talked about method signatures. Method signatures specify a list of parameters data types that a method expects to receive when it is called. For example, consider the familiar Math
method signature
sqrt(double)
It is illegal to call this method using sqrt(String)
because the method is not defined for String
arguments. A compiler error will result.
Knowing the sqrt()
method accepts doubles is not enough though. There are further requirements that must be true in order for the method to work properly. In particular, the input must be a non-negative double.
A precondition is a statement of everything that must be true when a method is called in order for the method to work properly.
In the case of sqrt(double)
, the precondition is: input must be a non-negative double. If a precondition is met and the method body is error-free, the method is guaranteed to work properly.
A postcondition is a statement of everything that is true when a method completes its job.
The postcondition for sqrt(double)
is that the square root of the input is returned.
It is important to document preconditions and postconditions as your programs become more complex. Preconditions go beyond parameter lists:
Anyone who uses your classes will need to know this information as well as the postcondition of what is true when your method completes its task. Likewise, postconditions go beyond return values:
For the labs in this lesson and thereafter you will be required to state each method's pre and post conditions whenever
Here's an example. A precondition statement is needed because the method only works properly if the preconditions have been met.
/**
* Precondition: initialize() has been called
* playerName is defined,
* gameLevel is an integer from 1 (easy) to 5 (hard)
* m >= 3, n >=3
*
* Postcondition: a new m by n tic-tac-toe board is displayed in the console
* window along with the player's name and difficulty level.
**/
void startGame(int m, int n) {
< method body >
}
Failure to provide preconditions and handle precondition violations led to a $500-million software error in 1996. You can read about the fate of the European Ariane 5 launcher here. Fortunately, Java provides a means for dealing with precondition violations and run-time errors.
Last modified: December 12, 2022
Dark Mode
Outline