52

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?

informatik01
  • 16,038
  • 10
  • 74
  • 104
Reddy
  • 8,737
  • 11
  • 55
  • 73
  • 2
    why would you want null? I understand when you query for a single result - not found would make sense to return null. But list() should always return an empty list! What is the meaning of a null list? – ACV Sep 14 '17 at 11:50

2 Answers2

107

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
  • 114,404
  • 31
  • 268
  • 329
  • 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 Aug 30 '10 at 10:20
  • 16
    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 Aug 30 '10 at 11:20
  • 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 Aug 30 '10 at 12:16
  • and if you want to skip code if the list is empty do not check size but if it is empty: list.isEmpty() (it is faster and more clear) – tibi Sep 26 '17 at 13:46
11

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

Sjoerd
  • 74,049
  • 16
  • 131
  • 175