Returning an empty collection instead of null

For one of my recent projects, I had to work with legacy code. There were methods that are returning collections, like lists or sets. These collections were created by reading data from the database. Whenever there is no data to form the collection, these methods return null. Now that is bad!

One of the issues of returning null is that the caller always have to check for null. Most of the time the caller either searches for a particular value in the returned collection or iterate through the elements in the returned collection. The code will look like this:

List rows = myDao.getRowsFor("key");
if(rows != null) {
  for(Row row:rows) {
    // Do something with the row

As you can see, it is easy to avoid the null pointer check if the getRowsFor() returned an empty list instead of a null pointer when there is no data in the database.

The clutter caused out of the null pointer checks all over the code. You can read more about this simple principle in Effective Java and an excerpt of that can be found here.


Popular posts from this blog

Note on allocationSize parameter of @SequenceGenerator while using JPA

The mysterious ORA-03111 error

Creating a Collection with a single element