Книга: Practical Programming, Fourth Edition
Назад: Choosing Test Cases
Дальше: Bugs We’ve Put in Your Ear

Hunting Bugs

Bugs are discovered through testing and program use, although the latter is what good testing can help avoid. Regardless of how they are found, tracking down and eliminating bugs in your programs is part of every programmer’s life. This section introduces some techniques that can make debugging more efficient and give you more time to do the things you’d rather be doing.

Debugging a program is like diagnosing a medical condition. To find the cause, you start by working backward from the symptoms (or, in a program, its incorrect behavior). Then, you come up with a solution and test it to ensure it fixes the problem.

To debug software, you have to know what it is supposed to do and be able to repeat the failure

At least, that’s the right way to do it. Many beginners make the mistake of skipping the diagnosis stage and attempting to cure the program by making random changes. Renaming a variable or swapping the order in which two functions are defined might fix the program, but millions of such changes are possible. Trying them one after another in no particular order can be an inefficient waste of many, many hours.

Here are some rules for tracking down the cause of a problem:

  1. Make sure you know what the program is supposed to do. Sometimes, this means doing the calculation by hand to verify the correct answer. Other times it means reading the documentation (or the assignment handout) carefully or writing a test.

  2. Repeat the failure. You can debug things only when they go wrong, so find a test case that reliably causes the program to fail. Once you have one, try to find a simpler one; doing this often provides enough clues to allow you to fix the underlying problem.

  3. Divide and conquer. Once you have a test that causes the program to fail, try to identify the first point at which something goes wrong. Examine the inputs to the function or block of code where the problem first becomes visible. If those inputs are not what you expected, look at how they were created, and so on.

  4. Change one thing at a time, for a reason. Replacing random bits of code on the off-chance they might be responsible for your problem is unlikely to do much good. (After all, you got it wrong the first time…) Each time you make a change, rerun your test cases immediately.

  5. Keep records. After working on a problem for an hour, you won’t be able to remember the results of the tests you’ve run. Like any other scientist, you should keep records. Some programmers use a lab notebook; others keep a file open in an editor. Whatever works for you, make sure that when the time comes to seek help, you can tell your colleagues exactly what you’ve learned.

Назад: Choosing Test Cases
Дальше: Bugs We’ve Put in Your Ear