Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guava Optional. How to use the correct

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.

like image 580
Aleksandr Avatar asked Dec 01 '22 23:12

Aleksandr


1 Answers

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.

like image 126
Louis Wasserman Avatar answered Dec 04 '22 12:12

Louis Wasserman