Java 8 避免空检查

Java 8 避免空检查


概述

null的发明者Tony Hoare在2009年致歉,表述了这个billion-dollar mistake

I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.

举例

  • 定义三层嵌套的类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    class Outer {
    Nested nested;
    Nested getNested() {
    return nested;
    }
    }
    class Nested {
    Inner inner;
    Inner getInner() {
    return inner;
    }
    }
    class Inner {
    String foo;
    String getFoo() {
    return foo;
    }
    }
  • 原始避免NullPointerException的方法很繁琐

    1
    2
    3
    4
    Outer outer = new Outer();
    if (outer != null && outer.nested != null && outer.nested.inner != null) {
    System.out.println(outer.nested.inner.foo);
    }
  • Java 8 使用Optinalmap,它接受一个Function,封装为Optional对象。

    1
    2
    3
    4
    5
    Optional.of(new Outer())
    .map(Outer::getNested)
    .map(Nested::getInner)
    .map(Inner::getFoo)
    .ifPresent(System.out::println);
  • 另一种通过Supplier方法 (个人不推荐主动捕获NullPointerException

    1
    2
    3
    4
    5
    6
    7
    8
    9
    public static <T> Optional<T> resolve(Supplier<T> resolver) {
    try {
    T result = resolver.get();
    return Optional.ofNullable(result);
    }
    catch (NullPointerException e) {
    return Optional.empty();
    }
    }
1
2
3
Outer obj = new Outer();
resolve(() -> obj.getNested().getInner().getFoo());
.ifPresent(System.out::println);

调用obj.getNested().getInner().getFoo()可能抛出NullPointerException
这里手动捕获了异常,并返回Optional.empty()

© 2017 Hello World All Rights Reserved. 本站访客数人次 本站总访问量
Theme by hiero