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?

1
  • 3
    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? Commented Sep 14, 2017 at 11:50

2 Answers 2

110

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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).
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.
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.
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)
Is there a hibernate reference that mentions this? That it is guaranteed that it will be an empty list and not null?
11

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.