Doesn't return anything using array == null or array.length == 0?

Suppose I have a function with the following signature:

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

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

+3
source share
5 answers

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

If any error occurs, you should throw it away Exception.

The reason is that users do not need to search for zeros:

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

, GetSomeFoos null, NullPointerException. , , .

+11

. API, , - , - .

0

null , . , , , ( Java ) . , - , .

, .

, , . :

private static final String[] EMPTY = {};

:

private static final List<String> EMPTY = 
    Collections.unmodifiableList(new ArrayList<String>());
0

.

( NPE) ( ).

0

Java (2- .) - 43: , nulls

, null array collection

0

Source: https://habr.com/ru/post/1766891/


All Articles