All books

Professional

Apps About Coach Log in Start reading

Computer Science · Glossary

What is Precondition, postcondition?

Also known as: precondition · postcondition

Definition 1.2 High School Computer Science · Chapter 1 — Specifications, Assertions and Tests

A precondition of a function is a condition on its arguments that the caller must make true before the call. A postcondition is a condition on the result (and on the arguments) that the function makes true when it returns, provided the precondition held.

The contract of a function. The caller’s duty comes first, the function’s duty after.
The contract of a function. The caller’s duty comes first, the function’s duty after.

Examples

Example 1.5 (The specification of a maximum)

For a function largest(t): the precondition is “t is a non-empty list of numbers”; the postcondition is “the result is an element of t, and no element of t is larger”. The empty list is excluded because it has no largest element: the specification forces the author to decide this case instead of leaving it to chance.

Example 1.11 (Tests for leap_year)

One year of each kind: 20232023, 20242024, 19001900, 20002000; the edge of the precondition: 15831583, which is not a leap year. Sam’s original function fails exactly one of these five tests, the one for 19001900. Any set of tests that misses the third kind misses her bug, however many years it contains.

Read in context →