views:

197

answers:

2

I need a cleaner solution to using an ImmutableSet. I have code that looks like

Set foo = ImmutableSet.copyOf(aGeoR.getFailed());

it works great when aGeoR.getFailed() returns one or more entries.

it fails when the returned set is null.

When its null, I need a

Set foo = ImmutableSet.of();

What is the clean way to do this?

+2  A: 
Set foo = aGeoR.getFailed();
foo = foo == null ? new HashSet() : ImmutableSet.copyOf(foo);
Jherico
Better than your suggestion would be:foo = foo == null ? ImmutableSet.of() : ImmutableSet.copyOf(foo);but that really isn't much cleaner, IMHO
fishtoprecords
The clean way to fix it is to change getFailed() to return a non-null value always or get Guava to accept a null value in its param. If you're dealing with two different libraries then your best bet is to use the adapter pattern to smooth over the inconsistencies or cope with the shear
Jherico
Guava, and the Collections stuff behind it really dislike null values. Its a design thing for them. And I tend to like it. Most of the time.
fishtoprecords
Why do you like null? For me it causes a lot of pain when libraries tend to return null instead of empty collections.
Willi
I suppose people who don't know about Collections.emptySet() fear to create tons of trivial sets and simply return null. Not a good idea, of course.
deepc
+9  A: 

This is phrased as a question about Guava and ImmutableSet, but the real issue here is with aGeoR.getFailed(). It is essentially never appropriate for a collection-returning method to return null. It should be returning an empty set to begin with (see Effective Java); and yeah, the fact that it isn't is going to cause some pain to users.

When I have to deal with an API like that, and I can't fix it or get it fixed, I do exactly what you showed in your revision of @Jherico's answer.

Set<FailedGeoR> failedOrNull = aGeoR.getFailed();
Set<FailedGeoR> failed = (failedOrNull == null)
    ? ImmutableSet.of()
    : ImmutableSet.copyOf(failedOrNull);
Kevin Bourrillion