Skip to content
Advertisement

More succinct code for a defensive copy using Guava’s immutable types?

I want to make a defensive copy of a collection passed into a method using Guava’s immutable types, e.g. an ImmutableList. I must also be able to deal with null input and treat that like an empty collection.

The cleanest I could come up with was this:

  public void setStrings(List<String> strings) {
     this.strings = strings == null ? ImmutableList.of() : ImmutableList.copyOf(strings);
  }

Is there something more readable, preferably without the ternary operator? I wouldn’t consider Optional.of(strings).map(...).orElse(...) as a nice alternative due to the reasoning that I share with this answer.

Advertisement

Answer

You can use MoreObjects.firstNonNull, which is also from Guava:

public void setStrings(List<String> strings) {
     this.strings = ImmutableList.copyOf(MoreObjects.firstNonNull(strings, Collections.emptyList()));
}

Alternatively ListUtils.emptyIfNull is a similar but more specialized method in Apache Commons Collections which is more clear and easier to read in my opinion:

public void setStrings(List<String> strings) {
     this.strings = ImmutableList.copyOf(ListUtils.emptyIfNull(strings));
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement