Null check

January 11th, 2006

Java developers are trained time and again to assert that objects are not null. This can result in weird Pavlov-like reflexes. Witness this snippet from a high-profile OSS project:

if (defaultValue != null) {
    return defaultValue;
} else {
    return null;
}

4 Responses to “Null check”

  1. Codepope Says:
    It could be worse... return defaultValue!=null?defaultValue:null; :)
  2. jim Says:
    why not? return defaultValue;
  3. Brian Says:
    Why not name the offending project? I'd like to know where you saw this.
  4. Sergey Says:
    This is MUCH better: try{ String str = defaultValue.toString(); } catch(NullPointerException ex){ return null; } return defaultValue;

Leave a Reply