What is the point of the Guava Option class

I read about it recently and saw people using this class, but in most cases using null also work - if not more intuitively. Could someone provide a concrete example where Optional will achieve something that null cannot or in a much cleaner way? The only thing I can think of is to use it with Maps , which do not accept null keys, but even this can be done with a lateral "display" of a null value. Can someone give me a more convincing argument? Thank.

+85
java generics guava
Mar 05 '12 at 3:32
source share
4 answers

Guava team member here.

Probably the biggest drawback of null is that it is not obvious what it should understand in any particular context: it does not have an illustrative name. It is not always obvious that null means “no value for this parameter” - heck, as the return value, sometimes it means “error” or even “success” (!!), or simply “the correct answer is nothing.” " Optional often represents is a concept that you really have in mind when you make a variable nullable, but not always. really mean.

But I would say that the biggest advantage of Optional not in readability: the advantage is its idiot proof. This makes you actively think about the missing case, if you want your program to compile at all, since you need to actively deploy Optional and refer to this case. Null makes it pretty simple to just forget something, and although FindBugs helps, I don't think it solves the problem almost as well. This is especially true when you return values ​​that may or may not be present. You (and others) are far more likely to forget that other.method(a, b) can return null than you probably forget that a can be null when implementing other.method . Returning Optional prevents callers from forgetting this case, as they must deploy the object themselves.

For these reasons, we recommend using Optional as the return type for your methods, but not necessarily in the method arguments.

(This, by the way, is completely outlined from the discussion here .)

+150
Mar 05 2018-12-12T00:
source share

It really looks like Maybe Monogram by Haskell.

You should read the following: Wikipedia Monad (functional programming) :

And read From Optional to Monad with Guava in the Kerflyn Blog , which discusses the optional Guava version used as a monad:




Edit: With Java8, there is a built-in optional that has monadic operators like flatMap . It was a moot point, but finally it was implemented.

See http://www.nurkiewicz.com/2013/08/optional-in-java-8-cheat-sheet.html

 public Optional<String> tryFindSimilar(String s) //... Optional<Optional<String>> bad = opt.map(this::tryFindSimilar); Optional<String> similar = opt.flatMap(this::tryFindSimilar); 

The flatMap operator is essential for providing monadic operations and makes it easy to bind calls that all return optional results.

Think about it, if you used the map operator 5 times, you would get Optional<Optional<Optional<Optional<Optional<String>>>>> flatMap , and using flatMap would give you Optional<String>

With Java8, I would prefer not to use Guava Optional, which is less powerful.

+9
May 25 '12 at 15:14
source share

One good reason to use it is that it makes your zeros very meaningful. Instead of returning zero, which can mean many things (for example, an error, or a failure, or empty, etc.), you can put the "name" in your zero. Take a look at this example:

allows you to determine the base POJO:

 class PersonDetails { String person; String comments; public PersonDetails(String person, String comments) { this.person = person; this.comments = comments; } public String getPerson() { return person; } public String getComments() { return comments; } 

}

Now let's use this simple POJO:

 public Optional<PersonDetails> getPersonDetailstWithOptional () { PersonDetails details = null; /*details of the person are empty but to the caller this is meaningless, lets make the return value more meaningful*/ if (details == null) { //return an absent here, caller can check for absent to signify details are not present return Optional.absent(); } else { //else return the details wrapped in a guava 'optional' return Optional.of(details); } } 

Now we avoid using null and perform our checks with the optional, therefore its significant

 public void checkUsingOptional () { Optional<PersonDetails> details = getPersonDetailstWithOptional(); /*below condition checks if persons details are present (notice we dont check if person details are null, we use something more meaningful. Guava optional forces this with the implementation)*/ if (details.isPresent()) { PersonDetails details = details.get(); // proceed with further processing logger.info(details); } else { // do nothing logger.info("object was null"); } assertFalse(details.isPresent()); } 

thus, after all, this is a way to make null values ​​meaningful and less ambiguous.

+6
May 6 '15 at
source share

The most important advantage of Optional is that it adds more detailed information to the contract between the developer and the calling function. For this reason, they are useful for parameters and return type.

If you make an agreement to always have Optional for possible null objects, you add additional explanations to such cases as:

  • Optional<Integer> maxPrime(Optional<Integer> from, Optional<Integer> to)

    The contract here clearly indicates that there is a likelihood that the result will not be returned, and will also show that it will work with from and to as absent.

  • Optional<Integer> maxPrime(Optional<Integer> from, Integer to)

    The contract indicates that from is optional, so a missing value can have a special meaning, such as starting at 2. I can expect that null for the to parameter will throw an exception.

Thus, the good part of using Optional is that the contract has become both descriptive (similar to the @NotNull annotation) and formal, since you have to write .get() code to handle Optional .

+4
Jun 10 '13 at 17:32
source share



All Articles