-1
\$\begingroup\$

I have such method:

@SuppressWarnings("unchecked")
public static <T, K> K[] toArray(ITemplateCommand<T, K> command, List<T> templates) {
    if (null == templates) {
        return (K[]) Array.newInstance(command.getClassOfK(), 0);
    }
    K[] array = (K[]) Array.newInstance(command.getClassOfK(), templates.size());
    for (int i = 0; i < templates.size(); i++) {
        array[i] = command.buildTemplate(templates.get(i));
    }
    return array;
}

Originally I had return null in block if (null == templates) but FindBugs recommended not to return null but array instead.

I am curious - should I leave it as it now or return to return null line?

\$\endgroup\$
4
\$\begingroup\$

Real answer to your question is not in the code that returns null, but in code that uses that result.

If returned null is significant signal and you have to execute some code based on that value (other than simply avoiding NPE) then you should return null. If code calling toArray could and would happily function properly if you return empty array instance, then returning empty array is preferred.

\$\endgroup\$
3
\$\begingroup\$

In general I always believe that although we use software like FindBugs to make us think and receive hints where improvement of our code might be usefull in the end it is up to us to decide. If you consider your code is better to understand the way you wrote it, you should keep it that way.

\$\endgroup\$
3
\$\begingroup\$

It's a recommended good practice to return an empty collection instead of null. If you return null, callers need an extra null-check when using the function.

null is a non-functional value. null is special. You can iterate over any collection, but not a null collection. If I can trust that a method returning a collection will never return null, then I can iterate over it without an extra null-check. If a method may return null, the extra null-check will inconvenience all callers.

This is not say that a method should never ever return null for a collection. It just says that when you choose to return null, you should have a good justification for that (it does happen too).

To conclude, if you have a specific reason to return null, then by all means, return null. Otherwise, follow the good advice and return an empty array.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.