Prev Main Next

Function Contracts

When you solve any problem, you need to know what the problem is before you solve it. It is silly to start working on a solution if you do not know what the problem is.

When you present a solution of a problem to somebody else, you should always say what problem you are solving. It is silly to present the solution without saying what it solves.

Functions solve problems. So it makes sense to write down the problem that the function solves. A clear and precise description of the problem that a function solves is called a contract for the function.


Example

The isprime function solves the following problem.

isprime(n) returns true if n is prime, and false if n is not prime. For example, isprime(4) is false, but isprime(5) is true.

The min function solves the following problem.

min(x,y) returns the smaller of x and y. If x and y are equal, then min(x,y) = x. For example

min(3,8) = 3
min(12,2) = 12
min(4,4) = 4


Rules for writing contracts


  1. Contracts must be written down, not kept in your head.


  2. Since you need to know what the problem is before you try to solve it, write the contract before you write the function definition.


  3. Write a contract as a comment in your program.


  4. Remember that contracts are supposed to be readable. So use correct spelling, punctuation and grammar.


  5. A contract tells what a function does (what problem it solves), not how the function works, or which tools the function uses.


  6. A contract must say what every parameter is for, and how it affects the problem.


  7. Do not use pronouns, such as it, or pronoun phrases, such as the number, in contracts. Pronouns tend to make your contracts vague and difficult to understand. Call things by their names.


  8. A contract must say what the function returns; otherwise, it is not a precise statement of the problem that the function solves.



Prev Main Next