使用Guava标准化丑陋的方法参数

jgm*_*jgm 0 java guava

我有一个包含可选项的类Map:

 private Optional<ImmutableMap<String, String>> stuff;
Run Code Online (Sandbox Code Playgroud)

在我的类构造函数中,我被传递Map<String, String> inputStuff,其中inputStuff可能是:

  • null
  • 一个空的 Map
  • 一个人口稠密的 Map

对于我需要存储的前两个实例Optional.absent(),对于第三个实例,我需要存储Optional地图的不可变副本.在处理这个方面我能想出的最好的是:

    final ImmutableMap<String, String> tmp = ImmutableMap.copyOf(Objects.firstNonNull(inputStuff, ImmutableMap.<String, String>of()));
    if (inputStuff.isEmpty())
    {
      this.stuff = Optional.absent();
    }
    else
    {
      this.stuff = Optional.of(inputStuff);
    }
Run Code Online (Sandbox Code Playgroud)

有没有更清洁的方法来处理这个?

Xae*_*ess 9

为什么不简单地做:

if (inputStuff == null || inputStuff.isEmpty()) {
  this.stuff = Optional.absent();
} else {
  this.stuff = Optional.of(ImmutableMap.copyOf(inputStuff));
}
Run Code Online (Sandbox Code Playgroud)

我没有看到你为什么要在这里创建临时变量的原因.如果您更喜欢使用三元运算符,您甚至可以避免重复的赋值this.stuff.

  • [`Iterables.isNullOrEmpty`](http://code.google.com/p/guava-libraries/wiki/IdeaGraveyard#Iterables.isNullOrEmpty)被Guava团队明确拒绝,请参阅[此答案](http:// stackoverflow .COM /问题/ 6910002 /谷歌番石榴isnullorempty换集合/ 6921270#6921270). (2认同)