Skip to content

Functional Java

Nimrod edited this page Dec 1, 2019 · 1 revision

How do I avoid lots of != null?

Checking for null is tedious, however unless you know a variable can't be null, there is a chance it will be null. There is @NotNull annotations available for FindBugs and IntelliJ which can help you detect null values where they shouldn't be without extra coding. Optional can also play a role now.

Say you have

if (a != null && a.getB() != null && a.getB().getC() != null) {
     a.getB().getC().doSomething();
}

Instead of checking for null, you an write

Optional.ofNullable(a)
        .map(A::getB)
        .map(B::getC)
        .ifPresent(C::doSomething);
Clone this wiki locally