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:
- whether or not to do so: the method parseAction (and similar) returns Optional ?
- whether or not to do so: the field of class objects Optional ?
- 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.
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,
Optionalis primarily used for two things: to make it clearer what you would’ve meant bynull, and in method return values to make sure the caller takes care of the “absent” case (which it’s easier to forget withnull). We certainly don’t advocate replacing every nullable value with anOptionaleverywhere 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.