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 set , 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_map_java () {
Map < String , String > emptyMap = Collections . emptyMap ();
assertTrue ( emptyMap . isEmpty ());
}
Google Guava @Test
public void return_empty_map_guava () {
Map < String , String > emptyMap = ImmutableMap . of ();
assertTrue ( emptyMap . isEmpty ());
}
Apache Commons @Test
public void return_empty_map_apache_commons () {
@SuppressWarnings ( "unchecked" )
Map < String , String > emptyMap = MapUtils . EMPTY_MAP ;
assertTrue ( emptyMap . 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 map, 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_map_java_exception () {
DomainObject domain = null ; // dao populate domain
Map < String , String > mapOfStrings ;
if ( domain != null
&& domain . getMap () != null
&& ! domain . getMap (). isEmpty ()) {
mapOfStrings = domain . getMap ();
} else {
mapOfStrings = Collections . emptyMap ();
}
//...
}
Use Guava Objects.firstNonNull private void return_empty_map_guava_exception () {
DomainObject domain = null ; // dao populate domain
Map < String , String > mapOfStrings = Objects . firstNonNull (
domain != null ? domain . getMap () : null ,
ImmutableMap .< String , String > of ());
//...
}
Apache commons MapUtils private void return_empty_map_apache_commons_exception () {
DomainObject domain = null ; // dao populate domain
Map < String , String > mapOfStrings ;
if ( domain != null && ! MapUtils . isEmpty ( domain . getMap ())) {
mapOfStrings = domain . getMap ();
} else {
mapOfStrings = MapUtils . EMPTY_MAP ;
}
//...
}
Return empty map posted by Justin Musgrove on 08 January 2014
Tagged: java and java-collections
Share on: Facebook Google+
All the code on this page is available on github:
ReturnEmptyMap.java