Jonas Bonér bio photo

Jonas Bonér

Specialist at Large.
Entrepreneur.
Hacker.
Public Speaker.
Powder Skier.
Obsessive Learner.
Jazz Addict.
Wannabee Musician.

Twitter LinkedIn Github

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();

    ...
}