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?
If your method
GetSomeFoos()actually ‘found’ 0 elements, then it should returnnew 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:
In the above case, if
GetSomeFoosreturnednull, a user will have to deal with anNullPointerException. 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.