Writing Function Contracts
A contract states which inputs a function accepts, which outcomes it promises, and which state it may change.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Describe the allowed call
A mean function can accept a nonempty sequence of numbers and return their arithmetic mean. If empty input is allowed, specify an absent result or documented exception. A guard clause can make this rule visible, but a caller should know it before reading the body.
Use a distinguishing example
The input 2, 4, 8 gives \(14/3\). An implementation truncating to four violates a contract that promises an unrounded floating result. Include a noninteger mean in testable inputs and describe delivery precision where it matters.[1][2]
Separate the promises made by caller and function
An integer pack size can be positive while an order quantity can also be zero. For packs_needed(10, 4) the contract should promise three packs because two hold eight and three hold twelve. State whether the input includes partially used packs, which would change the problem. Write the postcondition as \((r-1)b<q\le rb\) for \(q>0\), with zero handled separately. This identifies the smallest valid result and rules out an implementation that always adds one. See function postconditions.
Turn the promises into boundary tests
For pack size four, test orders zero, one, four, five and eight. They distinguish empty input, the first pack, exact division and the transition to another pack. Test zero pack size separately according to the public error policy. If errors have names or structured fields, specify the properties callers need and leave incidental message punctuation outside the contract. A review should find every input assumption either validated or documented for callers. See function preconditions.