Uses for Optional

前端 未结 14 1422
眼角桃花
眼角桃花 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:32

    The main point of Optional is to provide a means for a function returning a value to indicate the absence of a return value. See this discussion. This allows the caller to continue a chain of fluent method calls.

    This most closely matches use case #1 in the OP's question. Although, absence of a value is a more precise formulation than null since something like IntStream.findFirst could never return null.

    For use case #2, passing an optional argument to a method, this could be made to work, but it's rather clumsy. Suppose you have a method that takes a string followed by an optional second string. Accepting an Optional as the second arg would result in code like this:

    foo("bar", Optional.of("baz"));
    foo("bar", Optional.empty());
    

    Even accepting null is nicer:

    foo("bar", "baz");
    foo("bar", null);
    

    Probably the best is to have an overloaded method that accepts a single string argument and provides a default for the second:

    foo("bar", "baz");
    foo("bar");
    

    This does have limitations, but it's much nicer than either of the above.

    Use cases #3 and #4, having an Optional in a class field or in a data structure, is considered a misuse of the API. First, it goes against the main design goal of Optional as stated at the top. Second, it doesn't add any value.

    There are three ways to deal with the absence of a value in an Optional: to provide a substitute value, to call a function to provide a substitute value, or to throw an exception. If you're storing into a field, you'd do this at initialization or assignment time. If you're adding values into a list, as the OP mentioned, you have the additional choice of simply not adding the value, thereby "flattening" out absent values.

    I'm sure somebody could come up with some contrived cases where they really want to store an Optional in a field or a collection, but in general, it is best to avoid doing this.

提交回复
热议问题