8.1. The Design Process

The basic process for designing and implementing a function is a sequence of a few steps.

  1. First, understand the problem that this function solves well enough so that you can write a clear contract for the function. That can involve looking at examples and possibly drawing pictures of data structures. Write the contract down. Make sure that it is clear and precise. Do not embark on solving a poorly defined problem. That is a waste of your time.

  2. Next, look at examples, and ask how you might solve them. Use common sense. Think about what information you need to remember while carrying out the solution. Anything that you need to remember indicates the need for a variable in the algorithm. Be sure not to try to use one variable for two different purposes. Use any tools that you have learned for discovering algorithms that are appropriate for this problem.

  3. Now write the code, or implementation, of your algorithm. Be careful to follow your plan from step 2. Proofread your code to see that it makes sense. Do a sanity check. Try your code by hand on a small example by doing a hand simulation. Does it appear to work? If not, find out what is wrong and fix it.

  4. Test your function on a computer. See testing and debugging.

Sometimes you need to go back and forth across the steps. For example, if, while coding, you discover a flaw in your algorithm, back up to algorithm discovery. If you need to make a change in the problem that the function solves, then go back to step 1 and modify the contract.

It is tempting to skip directly to step 3. Experience has shown that to be a poor idea. It leads to many hours of wasted effort.