Debugging & Testing

IntermediateAbout 12 minProgramming & algorithms

Every programmer writes bugs. Good programmers are just good at finding them.

Three Kinds of Bug

  • Syntax errors — the code breaks the language's rules, like a missing bracket. The program won't run at all.
  • Runtime errors — the program starts, then crashes, for example by using a list index that doesn't exist.
  • Logic errors — the program runs fine but gives the wrong answer. These are the sneaky ones.

Debugging means finding and fixing errors. Testing means running a program on purpose to find them.

Choosing Good Tests

You can't test every possible input, so choose wisely. For "a score of 60 or more passes", test:

  • Normal values — 75, 30. Everyday cases.
  • Boundary values — 59, 60, 61. Right at the edge, where most bugs hide.
  • Extreme or unusual values — 0, 100, an empty list. Things the programmer may not have thought about.

For each test, decide the expected result first, then compare it with what the program actually does.

Find the bug

Run a test

InputExpectedActualResult

Debugging Strategies

  • Trace by hand. Go line by line, writing down every variable's value.
  • Display values as it runs. Add a temporary DISPLAY to see what's really happening inside a loop.
  • Shrink the problem. Find the smallest input that still goes wrong.
  • Explain it out loud. Describing the code line by line to someone else (or a rubber duck!) often reveals the bug.
  • Change one thing at a time, then test again.

Passing Isn't Proof

If every test passes, that only proves the program works for those inputs. That's why the choice of tests matters so much — and why programmers keep their tests and run them again every time they change the code, to make sure a fix didn't break something else.

Sharpen your tracing skills with Pseudocode Practice.

Check your understanding

5 quick questions. Pick one answer for each — you'll see why straight away.

  1. A program runs without crashing, but gives the wrong answer. What kind of error is that?

  2. "Students who score 90 or more get an A." Which test value is most likely to catch a bug?

  3. A procedure passed all 5 of its tests. What can you say for sure?

  4. Which is the best way to find where a loop goes wrong?

  5. A list procedure works for [3, 4, 5]. Which extra test is most useful?