Practice question · Put in order
Order the steps by which an assertion turns a distant, mysterious failure into a local, obvious one.
- The assertion fails at the exact moment the assumption is first violated
- Write it as an assertion immediately before the code that relies on it
- Run the program on the input that used to fail far downstream
- Fix the code that produced the offending value, not the code that tripped over it
- State the condition you believe must hold at this point in the code
Hints
- An assumption has to be articulated before it can be written down as a check.
- The point of the check is where it fires, and the fix belongs upstream of that point.
Show the answer
- State the condition you believe must hold at this point in the code
- Write it as an assertion immediately before the code that relies on it
- Run the program on the input that used to fail far downstream
- The assertion fails at the exact moment the assumption is first violated
- 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.
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
- A function takes a list and an index and returns the element at that index. Select every check that belongs…
- Assertions are usually compiled out of release builds, and input validation never is. Why treat them…
- Defensive programming favours failing loudly at the point of the error over continuing with a plausible…