Introduction to debugging
Testing is the process of running the program against test cases to try to uncover errors. Debugging is the process of looking for the cause of an uncovered error and then fixing it —once the cause has been found. Often the cause is far removed from the place at which the error manifests itself.
Some people hate debugging, seeing it as a long, arduous, and frustrating task, like looking for a needle in a haystack. Others enjoy it, seeing it as a problem solving activity that requires the skill of a detective, who looks for evidence and sifts through it, trying to find out who committed a crime.
There are two basic methods for tracking down a bug:
- Use the debugging feature of your IDE. In most IDEs, you can turn on the "debugger", which allows you to step through execution of the program one statement at a time, watching how the values of the variables change. You can also set "breakpoints", and then let execution run its course, and it will stop whenever a breakpoint is reached and let you investigate values of variables.
- Insert print statements at judiciously chosen places of the program. Then execute the program and analyze the output.
In this course, we concentrate on method (2), inserting print statements. The next item asks you to watch a few lectures on the CD ProgramLive. These lectures will step through the process of debugging a program. Some part of the program calls a function anglicize, which translates an integer into its English equivalent —e.g. 123 is translated into "one hundred twenty three". Function anglicize doesn't seem to be working properly, and debugging takes place to find, "out why.
Debugging maxims
ProgramLive, as well as the text Gries/Gries, present four maxims that help in tracking down bugs. Because they are important, we state them once more here:
- Debugging maxim 1. Place print statement at the beginning and end of the method that appears to have an error in it —to check whether its precondition is met and to check whether it returns the correct value.
- Debugging maxim 2. Glean as much information as possible from each exercise of test cases.
- Debugging maxim 3. Insert print statements at judiciously chosen places, in order to check values of variables.
- Debugging maxim 4. Deal carefully with interfaces, for they are the source of many errors.