Notice

╠ This is my personal blog and my posts here have nothing to do with my employers or any other association I may have. It is my personal blog for my personal experience, ideas and notes. ╣

Sunday, July 19, 2015

Whether to return null or empty list ?

I personally feel it will be great if we return an empty list instead of returning NULL.
Why ? Otherwise we have to put NULL check everywhere where we are going to use it. In JDK 7 their are several option are provided to handle this situation smartly. To read about it click here.

Come back to the point we are discussing about empty list/set/map.

Now what is the special about returning an empty list.

  if(list == null) {
     list = new ArrayList<String>();
  }

Empty List Objects
Each reference point to new empty list.

This above solution have some problem in some conditions and this is not refined yet. Just consider a practical case where we have to return empty list more than one place in our code. So as a result we ending up creating multiple objects and this object can be modified in later code which is not ideal . As this empty list represent NULL state of an object. This empty list should behave in that manner.NULL state means no existence of object. So we must complement empty list with that kind of behavior.


To complements the above mention behavior Java provide us method for List , Set and Map. Like emptyList(), emptySet() and emptyMap() in java.util.Collections class. 

These methods provide an empty List, Set or Map which are immutable and in entire objects graph of your application will have only one object of it.

So as a result of these features we cannot modify the list and no matter how many times we call these methods we will be referencing to one object only, which will add up to better performance both in terms of CPU and memory.

Collections empty list method object
All reference pointing to same object in memory

We can even initialize all List, Set and Map variables in our code with this java.util.Collections class empty methods. By this we can simply initialize the list when we actually want to populate them.

Lets see a snipped of code.

private List<String> carNames = Collections.emptyList();

// When we want to populate
if(carNames.equals(Collections.<String>emptyList()){
   carNames = new ArrayList<String>();
   carNames.add("BMW");
   carNames.add("Audi");
   carNames.add("Maybach");
}


By doing this simple steps we take care of NullPointerException and memory optimization.

Take decision today.

Happy coding.