Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 555
pierrotlefou Avatar asked Sep 29 '26 03:09

pierrotlefou


1 Answers

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.

like image 180
jjnguy Avatar answered Oct 01 '26 16:10

jjnguy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!