In continuation to a previous blog post Test Driven Development, we would like to discuss the Defensive Coding approach in this blog post.
Defensive programming is an approach to improve software quality by “Making the software behave in a predictable manner despite unexpected input or user actions". The software's behavior should be consistent even in undesirable conditions.
Defensive programming techniques are used especially when a piece of software could be misused mischievously, or inadvertently, to cause a catastrophic effect, which is likely to be the case.
One of the compelling reasons to perform defensive coding is that catching exceptions is computationally expensive. It is useful to follow techniques that allow the program to continue by gracefully handling the exceptional conditions, without throwing an exception.
Defensive coding also reduces the number of bugs and ensures code correctness.
The most widespread practice is to use guard statements like:
- Do not repeat the guard statements. We often tend to repeat code to perform validations. This repeated guard usage can lead to primitive obsession and wasted computational cycles.
- In such cases, it is always better to either include abstractions to perform the validations or extract the duplicates into separate and reusable checks.
- Since these validations are very crucial and spread across the code base, they should be kept intact. It also helps us to adhere to the DRY (Don’t Repeat Yourself) principle.
- Always wrap a third party library usage with our own gateways or proxies.