---
title: "Defensive Programming"
source: https://www.jemoka.com/posts/kbhdefensive_programming/
---

Facts Everybody writes bugs Debugging sucks Defensive Programming Tools + Techniques Use language features Specs, documentations, Test-Driven Development, unit testing Fail fast and loudly Systematic debugging Investing in tools Use Language Features Descriptors: static, final, pub./priv. Type checking: prevent type errors Automatic array bounds checking Memory management Compiler optimization Key idea: know what language features are available, why/when to use them. don&rsquo;t work against the language in circumventing them
Specs, Docs., TDD, Unit Tests How should it work: specs How does it work: docs How will I know it works: TDD How do I know it still works: unit tests These all force you to think about your code before!! you write it so then you can correct them as soon as possible.
Failing Fast and Failing Loudly The earlier you recognize there is a problem, the easier it is to fix it Problems not fixed can be lost, covered up, or even relied upon Learn from every failure How do we put this into practice Use asserts, exceptions, logging Fix/diagnose/track every bug, even if you choose not to fix it Add regression tests for every bug + run them regularly Systematic Debugging Systematic Debugging is a framework for debugging software.
Reproduce the bug Reduce the bug to the smallest possible, repeatable test case Faster test cases mean faster iterations in debugging Smaller test cases help eliminate possible causes for error Find the root cause Study data (logs, behavior, etc.), hypothesis, experiment, repeat Change code and data to get more information FIXING SYMPTOM IS NOT ENOUGH Fix the bug Add a regression test, and run all tests Reducing Test Case Start with the data that uncovered the bug Remove pieces of data until the bug no longer occurs Bracketing: create both a test case that fails and similar test cases that pass Binary search: remove/add back half of the data at a time Can work from either end: start with everything and reduce until disappearance, or start with only one line and build until bug Finding the Cause Trace through the program View intermediate results Every iteration of a for loop Input and output of a given function Tools to use assert() printing/logging a debugger binary search Tooling! Linter Fuzzer Sanitizer Valgrind DTrace
