Search code examples
javanullempty-list

return nothing , using array == null or array.length == 0?


Supposing I have a function with following signature:

Foo[] getSomeFoos() 
{
      //return null         --- option A 
      or 
      //return new Foo[0];  --- option B
}

What is the recommended practice to return the value indicating there is no elements returned? Any pros or cons for each option?


Solution

  • If your method GetSomeFoos() actually 'found' 0 elements, then it should return new Foo[0].

    If there was some sort of error, you should throw an Exception.

    The reason is because users shouldn't have to look for nulls:

    for (Foo f: GetSomeFoos()) {
        // do stuff
    }
    

    In the above case, if GetSomeFoos returned null, a user will have to deal with an NullPointerException. But, if you return an empty array, the code will never enter the loop, and the user will not have to deal with an exception.