Guava Optional. How to use the correct

14,302

Guava contributor here...

Any or all of these things are fine, but some of them may be overkill.

Generally, as discussed in this StackOverflow answer, Optional is primarily used for two things: to make it clearer what you would've meant by null, and in method return values to make sure the caller takes care of the "absent" case (which it's easier to forget with null). We certainly don't advocate replacing every nullable value with an Optional everywhere in your code -- we certainly don't do that within Guava itself!

A lot of this will have to be your decision -- there's no universal rule, it's a relatively subjective judgement, and I don't have enough context to determine what I'd do in your place -- but based on what context you've provided, I'd consider making the methods return Optional, but probably wouldn't change any of the other fields or anything.

Share:
14,302
Aleksandr
Author by

Aleksandr

Updated on July 05, 2022

Comments

  • Aleksandr
    Aleksandr almost 2 years

    I have a class

    private class TouchCommand {
      private int action;
      private int x;
      private int y;
    ...
    

    When the command is executed, it is necessary to verify the field values ​​- null / not null, and depending on it to produce longitudinal action. I want to use Options from Google Guava.

    Which solution is right? this:

    public boolean executeCommand() {
      Optional<Integer> optionalAction = Optional.fromNullable(action);
      ...
    

    or:

    private class TouchCommand {
      private Optional<Integer> action;
      private Optional<Integer> x;
      private Optional<Integer> y;
    ...
    

    Given that the call to parseAction may also return a null (or absent):

    TouchCommand touchCommand = new TouchCommand();
    touchCommand.mAction = parseAction(xmlParser.getAttributeValue(namespace, "action"));
    ...
    

    Questions:

    1. whether or not to do so: the method parseAction (and similar) returns Optional ?
    2. whether or not to do so: the field of class objects Optional ?
    3. whether or not to do so: when checking the fields of the class (assuming that they can be null) to convert them into objects Optional ?

    Thx.

  • Aleksandr
    Aleksandr almost 12 years
    I just thought to do a class field "Optional" is not correct. If this is also correct, then (I think) to store values ​​that can be null, is easier than converting each time value in the Optional, if needed verification.
  • Louis Wasserman
    Louis Wasserman almost 12 years
    I mean, it's not like it wouldn't work. But Optional carries overhead of its own that might not be desirable. It's really much better to optimize for maintainability and code readability here.