4

我有一堂课

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

执行命令时,需要验证字段值——null/not null,并根据它产生纵向动作。我想使用 Google Guava 的选项。

哪种解决方案是正确的?这个:

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

或者:

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

鉴于对 parseAction 的调用也可能返回 null(或不存在):

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

问题:

  1. 是否这样做:方法 parseAction (和类似的)返回 Optional ?
  2. 是否这样做:类对象的字段 Optional ?
  3. 是否这样做:检查类的字段时(假设它们可以为空)将它们转换为对象 Optional ?

谢谢。

4

1 回答 1

19

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.

于 2012-07-19T13:35:21.430 回答