views:

50

answers:

2

When there are no rows, both query.list() and criteria.list() are returning empty list instead of a null value. What is the reason behind this?

+2  A: 

It is consistant: a list is returned with all results, whether there are any or not.

Sjoerd
+6  A: 

The reason is not to force null checks in client code, in consistency with Effective Java 2nd Edition, Item 43: Return empty arrays or collections, not nulls.

This makes the client code simpler and less error-prone (and most likely the method implementation as well).

The null-return idiom is likely a holdover from the C programming language, in which array lengths are returned separately from actual arrays. In C, there is no advantage to allocating an array if zero is returned as the length.

Péter Török
hmm... but even as it is preventing null checks, we still have to check for the size of list...right?and also as a good practice, we always checks for null also (at least in our team).
Reddy
That's the point - if you are sure (based on the promises of an API) that a value can't be null, then you don't check for null. And no, you don't need to check for size. When you iterate the collection, it will just skip the iteration.
Bozho
okay... got it. If it is a null and as I client if I didn't check for it, NPE can bring down my app. But if it is an empty collection, it would just skip the logic and continue (as we generally check for size anyways). Thanks Peter and Bozho.
Reddy