Defensive Code is an overloaded term. Many articles revolve around topics like the fail fast principle where you verify the bounds of a function before proceeding. There are opinions about the effectiveness and maintainability of a code base with redundant checks. Still, the principle behind defensive code is that Murphy’s law is alive and well.
Anything that can go wrong will go wrong.
Think about what the caller of your code is going to do, how much you trust them and expect the worst. This requires you to have knowledge about what might be fragile within your code. But, if you defend only what you know, it is what you don’t know that will cause production to go down in the middle of the night.
You might be thinking to yourself, “How can I possibly write any code guarding against what I do not know?”
Let’s be clear, you only know what you know and that is ok. You are exactly where you need to be as a developer and if production goes down, take a deep breath and learn from it.
In the meantime, here are some resources that I have found useful:
- An intro – thoughts on defensive programming like null checks.
- Future proofing – spot code that might break in the future, should you fix it now?
- OWASP Top 10 – every web application should defend against these common vulnerabilities.
- Understanding Time zones – dates, time zones and time calculations will cause more bugs than you can imagine. Hint: Use a library for clarity like Noda Time.
- Currencies – if your application deals with them, be mindful and test all parts of the flow where money is calculated, displayed and stored.
Whether you subscriber to defensive coding, TDD, SOLID, DRY or any/all other terms for maintainable and resilient code, you need to learn from experience about what might go wrong. Get a head start by learning best practices and what others have learned. Still, you can write as many test cases as you want, but when you add that one line log statement that results in a null pointer taking down your service…Murphy will be smiling somewhere.