Sunday, 1 May 2011

Null Collections and the Special Case Pattern

In my last blog I covered the Special Case Pattern demonstrating a special case NullEmployee object in an employee details scenario. What it doesn’t cover is the
public List<Employee> getEmployeesBySurname(String surname)
method. This method must also adhere to the Special Case pattern and not return null when there’s no data available.

Fortunately, java.util.Collections is a big help here in that it provides a bunch of methods that return an empty collection type. These comprise:

  public static final <T> Set<T> emptySet()
public static final <K,V> Map<K,V> emptyMap() 
public static final <T> List<T> emptyList()

In our employee details scenario, we need to change the EmployeeDAO so that it returns an empty list if no data is available.

  public List<Employee> getEmployeesBySurname(String surname) {

List<Employee> employees = dbHelper.getEmployeesBySurname(surname);
if (isNull(employees)) {
employees = Collections.emptyList();

return employees;

private boolean isNull(Object o) {
return o == null;

Job Done!

No comments: