Alternative for Null Coalescing Operator

Viewed 3760

With Java, to safely access a deep nested reference like a.b.c.d.e, we'd usually have to specify null checks at each level or wrap in Optionals and use orElse(). (Unlike with languages like Kotlin/C# where a?.b?.c?.d?.e or similar works.

I was wondering if the following helper method could be a reasonable alternative:

public <T> T valueOrNull(Supplier<T> expression) {
    try {
        return expression.get();
    } catch (NullPointerException e) {
        return null;
    }
}

This can then be used safely with value = valueOrNull(() -> a.b.c.d.e).

Note: I understand that catching NullPointerExceptions is usually frowned upon because of performance reasons and more, but was wondering if the usage here would be a reasonable exception.

1 Answers
Related