ensoft-xx / google-collections

Automatically exported from code.google.com/p/google-collections
Apache License 2.0
0 stars 0 forks source link

Easy way to deal with null Iterables when looping #299

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
After seeing
http://stackoverflow.com/questions/1749687/stringutils-defaultstring-euphemism-f
or-collections
on StackOverflow, I was wondering if there would be any support for an easy
way of dealing with null iterables when looping. Nulls suck, but sometimes
we have to deal with them and a conveniently statically-importable utility
method for this might be useful.

My proposal might look something like adding this to Iterables:

  public static <T> Iterable<T> nullSafe(@Nullable Iterable<T> iterable)
  {
    return iterable == null ? Collections.<T>emptySet() : iterable;
  }

with test cases in IterablesTest:

  public void testNullSafeWithNullInput() {
      assertNotNull(Iterables.nullSafe(null));
      assertTrue(Iterables.isEmpty(Iterables.nullSafe(null)));
  }

  public void testNullSafeReturnsInputObjectWhenNotNull() {
      Iterable<String> input = create("a", "b");
      assertSame(input, Iterables.nullSafe(input));
  }

with the use case something like:

  Collection<Foo> items = some3rdPartyObject.getFoos();
  for (Foo currentFoo : nullSafe(items)) {
     // Do something
  }

No, the name 'nullSafe' isn't great, but I think the idea is useful.

Original issue reported on code.google.com by funk...@gmail.com on 18 Nov 2009 at 6:23

GoogleCodeExporter commented 8 years ago
This is a good example of a feature that is useful mostly for just one thing: 
interacting with a badly-written API.

We're not inclined to build such features into our library. Interacting with 
badly-
written APIs *should* be painful. That's what motivates the development of good 
APIs.

If we added this, many, many users would use it in situations where they'd be 
better 
off to just throw NPE, forcing the source of that null to root it out.

Sorry!

Original comment by kevinb@google.com on 8 Dec 2009 at 5:28