Return empty set

Effective java Item 43 states return empty arrays or collections, not nulls. In practice you should return the same immutable empty collection every time you return a collection. There are a few ways to handle the exception to the rule when you encounter methods that should return a collection but instead return null. Check out return empty list, return empty map, return empty enumeration, return empty list iterator, return empty sorted set, return empty sorted map and return empty iterator when having to deal with other collection types.

Straight up Java

@Test
public void return_empty_set_java () {

    Set<String> emptySet = Collections.emptySet();

    assertTrue(emptySet.isEmpty());
}

Google Guava

@Test
public void return_empty_set_guava () {

    ImmutableSet<Object> emptySet = ImmutableSet.of();

    assertTrue(emptySet.isEmpty());
}

Apache Commons

@Test
public void return_empty_set_apache_commons () {

    @SuppressWarnings("unchecked")
    Set<String> emptySet = SetUtils.EMPTY_SET;

    assertTrue(emptySet.isEmpty());
}

Exception to the rule

The goal is to handle the null to empty collection early in the chain. If you are coding the method that returns a set, there is no reason it should return null. When dealing with legacy code you have to deal with a null so here are a few options when that occurs:

Just make the null and empty check

private void return_empty_set_java_exception () {

    DomainObject domain = null; // dao populate domain

    Set<String> strings;
    if (domain != null
            && domain.getStrings() != null
            && domain.getStrings().size() > 0) {
        strings = domain.getStrings();
    } else {
        strings = Collections.emptySet();
    }
}

Use Guava Objects.firstNonNull

private void return_empty_set_guava_exception () {

    DomainObject domain = null; // dao populate domain

    Set<String> strings = Objects.firstNonNull(
            domain != null ? domain.getStrings() : null,
            ImmutableSet.<String>of());

    //...
}

Apache commons SetUtils

private void return_empty_set_apache_commons_exception () {
    DomainObject domain = null; // dao populate domain

    Set<String> strings;
    if (domain != null && !CollectionUtils.isEmpty(domain.getStrings())) {
        strings = domain.getStrings();
    } else {
        strings = SetUtils.EMPTY_SET;
    }

    //...
}