martedì 6 marzo 2012

Use assertions!

You use assertions, don't you?
Today almost every language/framework/library provides developers with an assertion-like set of tools. Use them!
The point is not that assertions are good for testing critical conditions, it is that they help documenting the code. Allow me to explain with an example:

private String doSomething( String input ){
     assert( input != null );
     return ;
}

What can you see here? That the input object cannot be null. Trivial. But there's more: developers are working here assuming someone has called doSomething with a null object argument, that is having input null is not only bad, it is a catastrophe! So if you are a doSomething client you are supposed to provide the right value for input arguments. 
Now, please remember that assertions are totally different from exceptions. The above method could have been written as:


private String doSomething( String input ){
     if( input == null )
         throw new Error();

     return ;
}

This is totally different: in the former method the developers clearly stated that they do not want to deal with a null input, it's on you to provide a not-null input object. In the above example instead developers are somehow dealing with null values, even if they are letting you to know that you did something wrong.
So when to use assertions and when to not use them? Assertions should be used for all the internal stuff, e.g., private methods, so things that should be called when input is not tainted. On the other hand, if you think you are going to get bad input, deal with it!
And remember: assertions are going to vanish when you are in release mode, so do not place anything more complex than a boolean test in them. For instance:

private void doSomethingElse(){
    assert( loadDataFromDatabase() != true );
    ...

This is ugly wrong! Once the assertion is disabled, chances are (depending on the assertion mechanism of the language/framework/library), that the call to loadDataFromDatabase disappears too, and with it all your loading-data!
So please use assertions, and use against single variables!

Nessun commento: