The Knowledge Institute
← Back to library

Programming Foundations · 1 MIN READ

Give a function examples it must pass

Define inputs and expected outputs before deciding that a reusable calculation works.

A function needs a contract

A function groups behavior behind a name and can return a result. Its contract states acceptable inputs, the output’s meaning, and how invalid input is handled. For a fictional materials estimate, define cost as quantity multiplied by unit price. Specify whether quantity may be fractional and whether prices already include tax. Reuse is valuable only when callers understand these assumptions.

Worked example: an estimate helper

Consider def estimate(quantity, unit_price): return quantity * unit_price. An ordinary test expects estimate(3, 12) to return 36. A zero-quantity test expects estimate(0, 12) to return 0. If negative quantities are forbidden, decide whether the function should reject them and implement that validation; the multiplication alone returns a negative number. A test that merely checks that the function runs would miss a wrong result.

Tests provide evidence within their scope

Write the expected result independently of the implementation. If a faulty helper adds its inputs, a test expecting 36 for inputs 3 and 12 catches it. A test that copies the same faulty addition into its expected result does not. Add boundary and invalid-input examples. Passing tests demonstrate those checked cases; they do not prove every possible input is handled. When a real failure occurs, preserve a small reproducing example as a regression test.

Put it to work

Design one ordinary case, one zero case, and one invalid-input case for a function that estimates paint from wall area.

Knowledge check

1. Which test can detect an incorrect calculation?
2. What does passing a small test set establish?

Sources & further reading