Snippets

V. Makhnutin Nested NPE Defence

Created by Вячеслав Махнутин

File First.java Added

  • Ignore whitespace
  • Hide word diff
+public class First {
+
+    public Second second;
+
+    public First(Second second) {
+        this.second = second;
+    }
+
+    public Second getSecond() {
+        return second;
+    }
+}

File Fourth.java Added

  • Ignore whitespace
  • Hide word diff
+public class Fourth {
+
+    private String someString;
+
+    public Fourth(String someString) {
+        this.someString = someString;
+    }
+
+    public String getString() {
+        return someString;
+    }
+
+}

File Second.java Added

  • Ignore whitespace
  • Hide word diff
+public class Second {
+
+    private Third third;
+
+    public Second(Third third) {
+        this.third = third;
+    }
+
+    public Third getThird() {
+        return third;
+    }
+}

File Test.java Added

  • Ignore whitespace
  • Hide word diff
+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);
+    }
+
+}

File Third.java Added

  • Ignore whitespace
  • Hide word diff
+public class Third {
+
+    private Fourth fourth;
+
+    public Third(Fourth fourth) {
+        this.fourth = fourth;
+    }
+
+    public Fourth getFourth() {
+        return fourth;
+    }
+}
HTTPS SSH

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