How to avoid null checking in Java?

后端 未结 30 3204
失恋的感觉
失恋的感觉 2020-11-21 04:43

I use object != null a lot to avoid NullPointerException.

Is there a good alternative to this?

For example I often use:



        
30条回答
  •  礼貌的吻别
    2020-11-21 05:16

    With Java 8 comes the new java.util.Optional class that arguably solves some of the problem. One can at least say that it improves the readability of the code, and in the case of public APIs make the API's contract clearer to the client developer.

    They work like that:

    An optional object for a given type (Fruit) is created as the return type of a method. It can be empty or contain a Fruit object:

    public static Optional find(String name, List fruits) {
       for (Fruit fruit : fruits) {
          if (fruit.getName().equals(name)) {
             return Optional.of(fruit);
          }
       }
       return Optional.empty();
    }
    

    Now look at this code where we search a list of Fruit (fruits) for a given Fruit instance:

    Optional found = find("lemon", fruits);
    if (found.isPresent()) {
       Fruit fruit = found.get();
       String name = fruit.getName();
    }
    

    You can use the map() operator to perform a computation on--or extract a value from--an optional object. orElse() lets you provide a fallback for missing values.

    String nameOrNull = find("lemon", fruits)
        .map(f -> f.getName())
        .orElse("empty-name");
    

    Of course, the check for null/empty value is still necessary, but at least the developer is conscious that the value might be empty and the risk of forgetting to check is limited.

    In an API built from scratch using Optional whenever a return value might be empty, and returning a plain object only when it cannot be null (convention), the client code might abandon null checks on simple object return values...

    Of course Optional could also be used as a method argument, perhaps a better way to indicate optional arguments than 5 or 10 overloading methods in some cases.

    Optional offers other convenient methods, such as orElse that allow the use of a default value, and ifPresent that works with lambda expressions.

    I invite you to read this article (my main source for writing this answer) in which the NullPointerException (and in general null pointer) problematic as well as the (partial) solution brought by Optional are well explained: Java Optional Objects.

提交回复
热议问题