If you had to choose your Favorite (clever) techniques for defensive coding, what would they be? Although my current languages are Java and Objective-C (with a background in C++), feel free to answer in any language. Emphasis here would be on clever defensive techniques other than those that 70%+ of us here already know about. So now it is time to dig deep into your bag of tricks.
In other words try to think of other than this uninteresting example:
if(5 == x)
instead ofif(x == 5)
: to avoid unintended assignment
Here are some examples of some intriguing best defensive programming practices (language-specific examples are in Java):
- Lock down your variables until you know that you need to change them
That is, you can declare all variables final
until you know that you will need to change it, at which point you can remove the final
. One commonly unknown fact is that this is also valid for method params:
public void foo(final int arg) { /* Stuff Here */ }
- When something bad happens, leave a trail of evidence behind
There are a number of things you can do when you have an exception: obviously logging it and performing some cleanup would be a few. But you can also leave a trail of evidence (e.g. setting variables to sentinel values like "UNABLE TO LOAD FILE" or 99999 would be useful in the debugger, in case you happen to blow past an exception catch
-block).
- When it comes to consistency: the devil is in the details
Be as consistent with the other libraries that you are using. For example, in Java, if you are creating a method that extracts a range of values make the lower bound inclusive and the upper bound exclusive. This will make it consistent with methods like String.substring(start, end)
which operates in the same way. You'll find all of these type of methods in the Sun JDK to behave this way as it makes various operations including iteration of elements consistent with arrays, where the indices are from Zero (inclusive) to the length of the array (exclusive).
So what are some favorite defensive practices of yours?
Update: If you haven't already, feel free to chime in. I am giving a chance for more responses to come in before I choose the official answer.