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:
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, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With