16C. Top-Down Design

There is a general principle of software design called top-down design.

If, while writing a definition of function f, you find yourself wishing that you had other functions (say, g and h), then assume that you already have g and h and continue writing f, using them. You can write definitions of g and h later.

For example, the distance between two points (x1, y1) and (x2, y2) in the plane is √(x1x2)2 + (y1y2)2. Written in a program, that might look like this.

  distance = sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2));
But if you assume that you have a function sqr(x) that returns x2, that becomes shorter.
  distance = sqrt(sqr(x1 - x2) + sqr(y1 - y2));
Top-down design tells you to write it in the shorter way and to think about writing sqr later.

Recursion can be viewed as a special case of top-down design. While you are writing a definition of power, imagine that you have a definition of power that you can use. Don't worry about whether it will be available; it will, because you are in the process of writing it!

But there is a catch. When writing a recursive definition, there are some limitations on the parameters that you can pass to recursive calls. We look at that issue in the next page.