Defensive programming as anti-pattern

If you want a solid system, then null pointers can be your friend. This may seem like a contradiction since solid systems should not have null pointer exceptions but it can be a way to make your system fail fast on code that is not correct instead of covering it up. To make this more clear, take a look at the following code:<code>
if (optimizer.getStatus().equals("done") {
// do your thing, not interesting for this blog
else {
// do something else
}


It is possible for this piece of code to throw a null pointer exception when the optimizer’s property is null. This check will then throw a null pointer exception and the users will be mad at you. A common solution for this problem is to start with the string method and then check this against the value that must be checked like so:<code>
if ("done".equals(optimizer.getStatus()) {
// do your thing, not interesting for this blog
else {
// do something else
}

If the optimizer’s status is now null, it will not throw a null pointer exception anymore, so it looks like the world is in harmony again and all seems well. But that is not the case at all. If the status field now is null, then the else will be invoked. If this is good and intended behaviour then you are all set. But if the optimizer’s status object was never ment to be null, and this was introduced by some refactoring or sloppy coding, then you are left with a system that may or may not be correct. You will never know untill perhaps later on, for instance when saving the state of the optimizer to the database. And then it can get quite hard to figure out where the mistake was first introduced.

If, however, you would have left the code like the original piece was, then the code would have failed much sooner. And it will have also told you in the stack trace which property was null. Normally it is better to use the defensive mode of programming by comparing the value like it is done in the second example, but if you know for sure that the content is not allowed to be null and should not be null, then a null pointer exception is not a bad thing at all. Fail fast, fail safe