As you start writing longer programs, you might find yourself spending more time debugging. The more code you write before you start debugging, the harder it is to find the problem.
Incremental development is a way of programming that tries to minimize the pain of debugging by developing and testing in small steps. The fundamental steps are:
- Always start with a working program. If you have an example from a book, or a program you wrote that is similar to what you are working on, start with that. Otherwise, start with something you know is correct, like
x = 5. Run the program and confirm that you are running the program you think you are running. This step is important, because in most environments there are little things that can trip you up when you start a new project. Get them out of the way so you can focus on programming.
- Make one small, testable change at a time. A testable change is one that displays something on the screen (or has some other effect) that you can check. Ideally, you should know what the correct answer is or be able to check it by performing another computation.
- Run the program and see if the change worked. If so, go back to step 2. If not, you’ll have to do some debugging, but if the change you made was small, it shouldn’t take long to find the problem.
With incremental development, your code is more likely to work the first time, and if it doesn’t, the problem is more likely to be obvious. And that brings us to the Sixth Theorem of Debugging:
The best kind of debugging is the kind you don’t have to do.
In practice, there are two problems with incremental development. First, sometimes you have to write extra code to generate visible output that you can check. This extra code is called scaffolding because you use it to build the program and then remove it when you are done. But the time you save on debugging is almost always worth the time you invest in scaffolding.
The second problem is that when you’re getting started, you might not know how to choose steps that get from
x = 5 to the program you’re trying to write. We’ll look at an extended example in Chapter 6.
If you find yourself writing more than a few lines of code before you start testing and you’re spending a lot of time debugging, you should try incremental development.