Function Preconditions

A precondition describes a property the caller is responsible for supplying when using a function under its stated contract.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Choose a meaningful assumption
  2. Run a revealing invalid case
  3. Derive a precondition from the method being used
  4. Put validation where the guarantee enters

Choose a meaningful assumption

An ordinary median routine may require at least one observation. A binary search may require sorted input. The first can be checked at constant cost for a list. Fully checking the second can cost more than performing a single search. Explain assumptions in the function contract.

Run a revealing invalid case

Searching unsorted input can return an answer on some early matches and fail on others. Test the validation boundary that promises sorted data, then reuse that validated collection as intended. This separates domain validation from the routine relying on it.[1][2]

Derive a precondition from the method being used

A two-pointer search for a target sum can discard the smallest value when its sum with the largest is already too small. This elimination is justified only if all remaining partners are no greater than the current largest. An unsorted input breaks that property. For instance, a target of nine exists in [1, 8, 2], while an implementation assuming sorted order may miss it by discarding one. See front-and-back scans for the proof obligation.

Put validation where the guarantee enters

Sorting or checking sortedness at each call can erase the benefit of a faster search. An internal helper can accept a previously validated sequence when the callers and ownership permit that guarantee. A user-facing entry point can reject unsorted input or sort it itself if the public meaning permits reordering. Test a bad input containing an otherwise valid answer. An empty sequence may still satisfy sortedness and require its own defined result. See function contracts for which guarantees belong to the public boundary.

References

  1. Python Software Foundation, Python Tutorial: Control Flow ↩
  2. Python Software Foundation, Python Language Reference: Execution Model ↩