The Optimized Null Check Pattern
A friend of mine showed me The Optimized Null Check Pattern™ yesterday (found in a piece of production code):
public static boolean isNull(Object obj) {
boolean isNull;
try {
obj.toString();
isNull = false;
} catch (NullPointerException e) {
isNull = true;
}
return isNull;
}
Then a colleague pointed out to me that a variation of the pattern (not as clean though) is actually used by Sun.
From the java.util.logging.LogRecord class:
public LogRecord(Level level, String msg) {
// Make sure level isn't null, by calling random method.
level.getClass();
...
}
Comments