Function Postconditions

A postcondition states what a caller can rely on after a function completes successfully for a valid input.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Describe both order and contents
  2. Check observable state too
  3. Assert the properties that identify a valid result
  4. Distinguish an allowed result from a unique result

Describe both order and contents

A sort function's output should be in ascending order and contain the same values with the same multiplicities. Output 1, 2 is sorted for input 2, 1, 2 but loses a copy of 2. A contract needs both conditions when duplication matters.

Check observable state too

A sorting function can promise a fresh result or an in-place update. Test whether the original sequence kept its elements in their original order and whether a second reference sees a change. Mutable values determine what counts as a separate object.[1][2]

Assert the properties that identify a valid result

For sorting, checking only that the result is ordered allows a broken implementation that returns an empty list every time. Sorting [8, 2, 2] also requires the same multiset of values, including both twos. A stable sort of records adds an order promise for values with equal keys. Build a test where the duplicate keys have different labels so you can observe that promise. See stability in practice.

Distinguish an allowed result from a unique result

A function may return any index containing a requested value. On [4, 2, 4] the result can be zero or two under that contract. A test demanding zero creates an undocumented requirement. Check index bounds and check that the indexed value equals four. If a caller relies on the earliest result, change the public postcondition to require it and add a repeated-value case. Define how absence is represented separately. See the first-match scan for the stricter rule.

References

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