Hibernate query.list() method is returning empty list instead of null value

50,030

Solution 1

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.

Solution 2

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

Share:
50,030
Reddy
Author by

Reddy

Exception in thread "main" java.lang.NullPointerException at com.reddy.Reddy.main(Reddy.java:4)

Updated on February 21, 2020

Comments

  • Reddy
    Reddy about 4 years

    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?

  • Reddy
    Reddy over 13 years
    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).
  • Bozho
    Bozho over 13 years
    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.
  • Reddy
    Reddy over 13 years
    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.
  • tibi
    tibi over 6 years
    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)