What is Defensive Coding ?
Defensive programming is an approach to improve code in terms of
- General code quality - Reducing the number of software bugs and problems.
- Making the software behave predictably against unexpected inputs and user actions.
Aspects of defensive coding
- 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.
- 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