What is Defensive Coding ?

Defensive programming is an approach to improve code in terms of

  1. General code quality - Reducing the number of software bugs and problems.
  2. Making the software behave predictably against unexpected inputs and user actions.

Aspects of defensive coding image

  1. Readable code generally implies the code follows good naming conventions. Variables, classes and methods are all well named. Methods are short, reusable and contain no duplication (DRY). Code is well formatted, documented and organized. The code makes proper use of comments.
  2. In general quality we have cohesion and coherence. High cohesion is desired (Single-responsibility principle). Our code is easy to change and extend - well refactored. It makes use of the standard battle tested design patterns. Also, we have a suite of maintainable tests. Our focus is more on the third aspect of defensive programming.

Why defensive coding ?

“The whole point of defensive programming is guarding against errors you don’t expect.” - Steve McConnell, Code Complete

Errors cost time and money. The longer it takes to discover a bug, the more expensive the bug is. It is very easy to fix bugs before actual code implementation, bugs caught during unit testing are also easy to fix , still easier to fix bugs caught by QA in their test environments. But a production bug is more time-consuming and expensive to fix. Defensive coding deals with bugs during the development stage to prevent bugs further down the cycle.

tl;dr: Sooner a bug is caught, the better.


So how do we defend against bugs? Most of the actions we can take can be grouped into

  1. Reacting
  2. Preventing