Chapter 142

Home

Refactoring: Defensive Coding

The best bug fix is the bug that never happens. Defensive coding makes assumptions explicit and catches mistakes at runtime instead of in WA verdicts.

Before: Fragile code

C++ — vulnerable to subtle bugs

int arr[100];
int n; cin >> n;  // if n > 100 → buffer overflow!

After: Defensive patterns

C++ — defensive coding

// Use vector instead of fixed arrays
vector arr(n);  // dynamic, bounds-checked with .at()

// Assertions for debug
assert(n > 0 && "n must be positive");
assert(arr.size() == n);

// const for invariants
const int MOD = 1e9 + 7;

// Structured bindings for clarity
auto [min_val, max_val] = minmax_element(arr.begin(), arr.end());

// Early returns for edge cases
if (arr.empty()) return 0;

// Always use braces
for (int x : arr) { total += x; }  // not: for (...) total += x;