Snippets

V. Makhnutin Nested NPE Defence

Created by V. Makhnutin
public class First {

    public Second second;

    public First(Second second) {
        this.second = second;
    }

    public Second getSecond() {
        return second;
    }
}
public class Fourth {

    private String someString;

    public Fourth(String someString) {
        this.someString = someString;
    }

    public String getString() {
        return someString;
    }

}
public class Second {

    private Third third;

    public Second(Third third) {
        this.third = third;
    }

    public Third getThird() {
        return third;
    }
}
import java.util.Optional;

public class Test {


    public static void main(String[] args) {

        First notNull = new First(new Second(new Third(new Fourth("Not Null String"))));
        First nestedNull = new First(new Second(new Third(null)));

        System.out.println(get(notNull).orElse("is null"));

        System.out.println(get(nestedNull).orElse("is null"));

        String test = get(nestedNull).orElse(null);
        System.out.println(test);

    }


    private static Optional<String> get(First first) {
        return Optional.ofNullable(first.getSecond())
                .map(Second::getThird)
                .map(Third::getFourth)
                .map(Fourth::getString);
    }

}
public class Third {

    private Fourth fourth;

    public Third(Fourth fourth) {
        this.fourth = fourth;
    }

    public Fourth getFourth() {
        return fourth;
    }
}

Comments (1)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.