The How to Design Functions Recipe
There’s an interesting course at Coursera — Introduction to Systematic Program Design — that teaches a spesific design process for programming. The course uses Racket, a Scheme dialect, but the design techniques are easily transferable to any language.
One of the fundamental ideas is a design method for constructing functions. The link describes the process in detail, I will illustrate a simplified process using JavaScript.
Let’s say you are to implement a function that computes the factorial of a number.
Step 1: Signature, purpose and stub #
The first step is creating the signature for the function. A signature is simply a statement of the type of the input argument and the output argument. In our case that is: Number -> Number
.
The purpose is a short description of what the function does, in our case: computes the factorial of n
Nest we make a stub, the outer shell of the function with a dummy return value, which should be of the right type.
// Number -> Number
// computes the factorial of n
fact = function(n) {
return 0
}
Step 2: Define examples/tests #
Next we provide examples for how the function should work.
debug(fact(5) === 120)
debug(fact(0) === 1)
Step 3: Using the stub/template, write the function #
// Number -> Number
// computes the factorial of n
fact = function(n) {
var res = 1;
if (n > 1) {
for (var i = 1; i <= n; i++) {
res *= i;
}
}
return res;
}
debug(fact(5) === 120)
debug(fact(0) === 1)
Step 3: Test, debug and refactor #
Running the tests, they both return true. Looking at the function some more we see that it can be shortened. Finally, we have:
// Number -> Number
// computes the factorial of n
fact = function(n) {
var res = 1;
for (var i = 2; i <= n; i++) {
res *= i;
}
return res;
}
debug(fact(5) === 120)
debug(fact(0) === 1)
We run the tests again and see that they still return true.
The process has a lot in common with test driven development of course, but it’s nice to see that it can be implemented so easily in JavaScript without using any test library.