Demystifying Defensive Programming: A Modern Approach to Bulletproof Code
Is it a myth? A sophisticated way of programming? Or an obsessive concern for errors?
Lately, I’ve come across the term “defensive programming” in various places, and it seems to be gaining traction in the programming world. This article aims to discuss this intriguing concept, provide insight into how it can change the way you write your code, and introduce you to some essential principles that make up defensive programming. Chances are, you might already be familiar with some of these concepts; defensive programming leverages them to create code that can withstand future failures.
So, without further ado, let’s delve into this fascinating concept of defensive programming.
Defensive Programming: The Concept
Defensive programming is a coding approach where the developer anticipates potential problems that might arise in the code. This foresight, enabled by the defensive programming methodology, allows for the prevention of future errors and, more importantly, ensures that if errors do occur, the program won’t crash catastrophically.
In essence, defensive programming doesn’t revolve around the utopia of writing infallible code. Instead, it focuses on the premise that when our applications inevitably fail (remember, nobody is perfect), the error occurs within a controlled environment. If defensive programming were a popular saying, it would be:
Failing with style
To achieve this, the code we write must:
- Fail safely, meaning that after a failure, no open or locked files should remain or any unfinished transactions against the database.
- Fail clearly, always providing an error code and a message explaining the root cause of the failure, making it easier to detect and fix. Additionally, providing a call stack and invocations is always a great idea.