Computer Science I / Defensive Programming and Debugging
Practice question · Put in order

Order the steps by which an assertion turns a distant, mysterious failure into a local, obvious one.

Hints
  1. An assumption has to be articulated before it can be written down as a check.
  2. The point of the check is where it fires, and the fix belongs upstream of that point.
Show the answer
  1. State the condition you believe must hold at this point in the code
  2. Write it as an assertion immediately before the code that relies on it
  3. Run the program on the input that used to fail far downstream
  4. The assertion fails at the exact moment the assumption is first violated
  5. Fix the code that produced the offending value, not the code that tripped over it
Why

Assertions work by making an implicit assumption explicit and checkable, so the program halts where the assumption first breaks rather than where the corrupted value later causes visible nonsense. The last step matters most: the assertion identifies the victim, and the bug is in whatever produced the bad value.

Read the lesson: Defensive Programming and Debugging →

Practise Defensive Programming and Debugging

The app has 7 more questions on this lesson, and keeps your place in the course. Computer Science I is free to start.

More questions on Defensive Programming and Debugging