10 Debugging¶
Debugging: The act of being the detective in the crime movie where you are also the murderer.
Recall... testing reveals a falut in a program, and debugging reveals the cause of that fault. Debugging takes mroe time than programming, so try to get it right the first time.
Some advice: follow the scientific method
- formulate a falsifiable hypothesis
- create an experiment that can refute that hypothesis
- find the simplest possible input that causes that fault
- run that experiment
- keep a notebook
If you get flummoxed
- The bug is probably not where you think it is
- Get someone to help you. Use duck debugging. Verbalize. Talk to someone outloud. Explain the problem to something as if it's a right computer.
- If all else fails, doubt your sanity: Do you have the right compiler? Is this the right source code?
- Don't debug when angry or tired. It makes things harder.
- Think through fixes carefully. "Fixing" a bug often introduces more bugs
Defensive programming¶
- proactive debugging: make it easier to detect faults by writing fault-detection code during implementation
- Assert your preconditions and invariants
- Write exhaustive conditionals (if/match)
Q. Isn't this expensive?
A. No! It only seems like that.
- For the implementer: the defensive code you write tends to pay off in the faults it catches early
- For performance: the faults you catch in production might save more money then the run-time cost of the checks.