Uses for Optional

前端 未结 14 1415
眼角桃花
眼角桃花 2020-11-22 01:01

Having been using Java 8 now for 6+ months or so, I\'m pretty happy with the new API changes. One area I\'m still not confident in is when to use Optional. I se

14条回答
  •  被撕碎了的回忆
    2020-11-22 01:30

    I think the Guava Optional and their wiki page puts it quite well:

    Besides the increase in readability that comes from giving null a name, the biggest advantage of Optional is its idiot-proof-ness. It forces you to actively think about the absent case if you want your program to compile at all, since you have to actively unwrap the Optional and address that case. Null makes it disturbingly easy to simply forget things, and though FindBugs helps, we don't think it addresses the issue nearly as well.

    This is especially relevant when you're returning values that may or may not be "present." You (and others) are far more likely to forget that other.method(a, b) could return a null value than you're likely to forget that a could be null when you're implementing other.method. Returning Optional makes it impossible for callers to forget that case, since they have to unwrap the object themselves for their code to compile. -- (Source: Guava Wiki - Using and Avoiding null - What's the point?)

    Optional adds some overhead, but I think its clear advantage is to make it explicit that an object might be absent and it enforces that programmers handle the situation. It prevents that someone forgets the beloved != null check.

    Taking the example of 2, I think it is far more explicit code to write:

    if(soundcard.isPresent()){
      System.out.println(soundcard.get());
    }
    

    than

    if(soundcard != null){
      System.out.println(soundcard);
    }
    

    For me, the Optional better captures the fact that there is no soundcard present.

    My 2¢ about your points:

    1. public Optional findFoo(String id); - I am not sure about this. Maybe I would return a Result which might be empty or contain a Foo. It is a similar concept, but not really an Optional.
    2. public Foo doSomething(String id, Optional barOptional); - I would prefer @Nullable and a findbugs check, as in Peter Lawrey's answer - see also this discussion.
    3. Your book example - I am not sure if I would use the Optional internally, that might depend on the complexity. For the "API" of a book, I would use an Optional getIndex() to explicitly indicate that the book might not have an index.
    4. I would not use it in collections, rather not allowing null values in collections

    In general, I would try to minimize passing around nulls. (Once burnt...) I think it is worth to find the appropriate abstractions and indicate to the fellow programmers what a certain return value actually represents.

提交回复
热议问题