This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Question: How do I use the Optional class?

Having been using Java8 for over six months now, I am very pleased with the new API changes. One area I’m still not sure about is when to use the Optional class. I want to use it everywhere, but I’m not sure if it’s the right way?

There seemed to be a lot of situations where I could use it, and I was never sure if it increased the benefit (readability/null security) or just caused extra overhead.

So, I gave you a couple of examples, and I’m interested in you guys denying that Optional is beneficial for code?

  1. When the return value may benullwhen
public Optional<Foo> findFoo(String id);
Copy the code
  1. When the parameter isnullwhen
public Foo doSomething(String id, Optional<Bar> barOptional);
Copy the code
  1. As a member of a bean
public class Book {

  private List<Pages> pages;
  private Optional<Index> index;

}
Copy the code
  1. Put it in the set
List<Optional<Foo>>
Copy the code

But does Optonal have any good use in collections?

Popular answers

Optional’s main design goal is to provide a way for functions that return a value to indicate that they do not. This allows the caller to continue a series of Fluent method calls.

This is closest to use case 1 in the OP problem. Still, missing values are more accurate than null, because something like Intstream.findFirst will never return NULL.

For use case 2, passing Optional to a method is feasible, but rather unwieldy. Suppose you have a method that takes a string followed by a second string of type Optional. Accepting Optional as the second argument results in the following:

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

It’s even better to accept a NULL

foo("bar"."baz");
foo("bar".null);
Copy the code

The best way to do this is to use overloading, which takes a single string argument and provides a default value for the second argument:

foo("bar"."baz");
foo("bar");
Copy the code

This does have limitations, but it’s better than any of the above.

Use cases #3 and #4, using Optional in class fields or collections, are considered API abuses. First, it violates Optional’s main design goals, as outlined at the top. Second, it adds no value.

I’m sure some people might come up with artificial examples where they really want to store Optional in a field or collection, but in general, it’s best to avoid doing so.

The article translated from Stack Overflow:stackoverflow.com/questions/2…