Staring me in the face

I’ve been working on a feature in our Android app for a while now. Every now and then, we’d get an app crash due to a NullPointerException being thrown here:

switch (mMeta.optString("type", null)) {
    case "a":
        return Type.A;
    case "b":
        return Type.B;
    case "":
        return Type.OTHER;
    default:
        return Type.UNKNOWN;
}

mMeta is guaranteed to exist, and while the observant amongst you might immediately see the problem, it stumped us. We couldn’t reliably replicate the problem, and with no obvious cause of the error, we decided to go ahead and launch, knowing that it might come back to bite us. Fortunately, we have all our features behind flags, and when it did rear its ugly head, we were able to turn it off pretty quickly.

I saw the error come up in the logs, took a look, and the problem immediately hit me. You can’t switch on a null in Java, and we were explicitly asking it to!

Ensure that the expression in any switch statement is not null to prevent a NullPointerException from being thrown.

Fortunately, the resolution to this problem is pretty straight forward, and one that we really should have seen a week ago when we first saw the issue.

String type = mMeta.optString("type", null);

if (type == null) {
    return Type.UNKNOWN;
}

switch (type) {
    case "a":
        return Type.A;
    case "b":
        return Type.B;
    default:
        return Type.OTHER;
}

Anyway, that’s my stupid lesson for the day!

Your email address will not be published. Required fields are marked *

HTML is not allowed (it'll appear as typed), but you can use Markdown instead. For the unitiated, paragraphs will be auto-inserted, but links won't be converted unless you [write them properly](http://example.com/).