
PRACTICAL PROGRAMMING ADVICE
2 Defensive Coding Techniques You Should Use Today
Simple but powerful techniques for safe, maintainable software
I’ll keep this one short and sweet.
We’ll be going over two very simple and practical defensive techniques you can start applying to your project today.
As a professional developer, chances are you’re already applying these techniques, so you might want to sit this one out.
However, for anyone who’s yet to reach a professional level, these techniques will improve your quality and make your code safer.
If you’ve never heard of defensive coding before, it’s about time. Here’s the gist of it.
Defensive coding allows our software to behave in a correct manner, despite incorrect input.
Right, let’s look into how you can make your software behave nicely, even when it’s provided with wrong inputs.
Guard Clauses — checking preconditions
These one-liners are one of the absolute cornerstones of defensive coding. They sit at the top of your methods making sure the methods only continue executing when valid input is provided.
They’re precondition checks. Here’s a very simple example, but nonetheless a real one.

We’re simply checking to see if the caller has provided us with a non-null or empty value. We’d typically do this if proceeding with such values might cause unexpected results.
You’ll need to refactor to another guard clause approach when your methods start to take a lot of arguments, or, one argument calls for multiple guard clauses. Such refactoring may involve creating an object that holds all the properties needed, as well as a IsValid() method. Here, the IsValid()` method is checking its state to validate if every property has valid values.

This refactoring technique is especially useful when you find yourself repeating the same guard clauses in multiple methods. A specification object, for instance, allows you to capture business rules in one place.
Assertions inside methods
You’re quite familiar with assertions. Those statements at the end of unit tests. In defensive coding, they’re not restricted to testing.
You’ll likely be calling other class methods and even methods provided by external libraries. In such cases, we’d like to check if our assumptions about what those methods do or return are true, before continuing with our method execution.

We anticipate errors. Adding anif after invoking the database’s Save() method, we effectively assert what happened, and act accordingly. No surprises.


Nicklas Millard is a software development engineer in one of the fastest-growing banks, building mission-critical financial services infrastructure.
Previously, he was a Big4 Senior Tech Consultant developing software for commercial clients and government institutions.
Connect on LinkedIn
