Not returning a null list but also not returning an immutable empty one and alternative approaches

52 views Asked by At

I have a method that returns a List.
E.g.
List<Foo> getItems(Bar bar, X x)

I don't want the method to return null to avoid null pointer exception and do something like:

List<Foo> getItems(Bar bar, X x) {
   if(!bar.conditionA() || !x.conditionB()) {
     return new ArrayList<>();  
   }
}

Note that the calling code uses the returning list to merge it with other lists.
E.g.

List<Foo> result = getItems(bar, x);
result.addAll(getFoo());  
result.addAll(getAll());  
result.addAll(getItems(bar, x));  
etc
 

My question is the following: from what I have seen some think that it is more optimal to return e.g. Collections.emptyList() to avoid instantiating a new list, but the issue is that if I change to follow that then the calling code becomes I think more complicated because the Collections.emptyList() is immutable so the calling code should be:

List<Foo> result = getItems(bar, x);
if(!result.isEmpty()) {
   result.addAll(getFoo());  
   result.addAll(getAll());
 }  
etc

which to me seems a bit more tedius.

Is there another way to handle both approaches nice?

0

There are 0 answers