Chapter 1: On the Defensive
Mull It Over
Can you have too much defensive programming?
Yes—just as too many comments can degrade code readability, so can many defensive checks, if they are bad. Redundant checks can be avoided with careful coding; for example, by making a good choice of types.
Should you add an assertion to your code for every bug you find and fix?
Fundamentally, it’s not a bad practice. But think about where you’d add the assertions. Many, many faults are due to incorrect honoring of API contracts. If you passed garbage into a function, you would want to put some precondition checking inside that function, rather than put a test at the call site. If the function returned garbage, you would either fix the function so that it won’t again ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access