Tino APCS

Preconditions and Postconditions

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.

Preconditions

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.

Postconditions

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:

  • Does your method depend on the state of an instance variable?
  • Are you expecting one method to be called before another one?
  • Does your method work only for a certain range within the parameter data types?

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:

  • Does your method modify an instance variable?
  • Does your method modify the contents of its input arguments? You need to say so if it does.

For the labs in this lesson and thereafter you will be required to state each method's pre and post conditions whenever

  • A method works only for a range of values less than its declared data type
  • A method makes any assumptions in order to work properly

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