Chapter 1: On the Defensive

Mull It Over

  1. 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.

  1. 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 ...

Get Code Craft now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.