Using Assertions to Debug Data Flow

A debugging assertion records an expected property at a point where a wrong value can still be connected to its cause.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Find the closest invariant
  2. Distinguish diagnostic assertions from validation
  3. Check one assumption just before it is used
  4. Treat external input failures as ordinary validation

Find the closest invariant

Suppose a batch contains an invalid negative size after processing. Check the size just after parsing and again just after each normalization step. The first failing check narrows the origin of the bug. Tracing program state gives a way to place those checks systematically.

Distinguish diagnostic assertions from validation

Python assertions can be omitted under optimization. Check untrusted or ordinary invalid input explicitly and return a documented outcome. This is a separate responsibility from domain validation at the interface.[1]

Check one assumption just before it is used

A calculation dividing by an item count can inspect whether the list actually contains results. An assertion that the count remains equal to the result length helps locate where a stale counter first diverged. Place it immediately after the update that should preserve the invariant. See loop invariants.

Before append: count=2, length=2
After faulty append: count=2, length=3
Invariant fails immediately, before the later average calculation

Treat external input failures as ordinary validation

Assertions can be disabled in some runtimes and should not be the only check for malformed data. Use them to express internal assumptions during investigation and test the real boundary behavior with explicit error outcomes.

References

  1. Python Software Foundation, unittest: Unit Testing Framework ↩