Demystifying Defensive Programming: A Modern Approach to Bulletproof Code

Is it a myth? A sophisticated way of programming? Or an obsessive concern for errors?

Gerardo Fernández

--

Photo by Charlein Gracia on Unsplash

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:

  1. Fail safely, meaning that after a failure, no open or locked files should remain or any unfinished transactions against the database.
  2. 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.
Photo by Towfiqu barbhuiya on Unsplash

Why We Need Defensive Programming

--

--

Gerardo Fernández

Entre paseo y paseo con Simba desarrollo en Symfony y React