Defensive programming

Defensive programming is important when it comes to building robust applications: you simply test the information which is coming in. Within an application you couldn’t simply say “Garbage in is garbage out”. You’re method should be robust, and in case of an error even log this problem. The values that you’re method will accept are the so-called preconditions of your method. These preconditions are also used by programming by contract.

When it comes to defensive programming. It is important to test all your public methods on the information that is passed. For example when you get passed an object, you want to check if the object is not null. Or when you’re writing a method that calculates a temperature from Kelvin to Celsius, you simply test if the provided temperature in Kelvin doesn’t exeed the 273 degrees.

On the other hand private members doesn’t realy need to be programmed defensive, since you are only the one who is calling these internal methods. Terefore it should be better to use assertions within your private members. Assertions will only be active within a debug build and throw an exception if the condition of the assertion is not met.

How do you handle an error that you do not expect to occur? If there is really, really something wrong you can’t deal with at the current level you throw an exception. You should however always try to fix the error locally. In all other cases you best return a decent value or provide an error code. When for example you’ve created a method that only excepts digits smaller than 10, you could argue that if someone is passing the number 11, your application uses 10 internally.

Posted in Best practices by Bruno at June 27th, 2012.

Leave a Reply