Is it correct to create a new object to throw a null pointer exception?

I don't want to pass the value null

to the presentation layer, so if I do something like:

  public List<Object> getListObjFoo(){
    List<Object> listObj = datasource.getAll();
    return listObj != null ? listObj : new ArrayList<Object>();


should be considered good or bad practice? and is using "Optional" in Google's "Guava" better than doing that? why?


source to share

3 answers

Your code is bad practice because it allocates a new instance. Try using Collection.emptyList()


Disadvantage: If the consumer of your code wants to change the list, they need to make a copy of the list. But this is a good practice, since many frameworks return immutable lists and as a consumer, you can never be sure unless the API actually tells you what you are allowed to do with the result.

The return null

is bad because it exports the implementation detail of your code to the consumer. Or put another way: if you change your implementation and suddenly find that you want to return null

, you will probably need to add checks in all places where the API is used. Thus, it hinders your ability to evolve your code and your API.

For other (non-collectible) types, you should look at the "optional" pattern, as described here: / ...

This pattern allows you to tell the consumers of your API that a method can return "nothing" without returning null

. This way, consumers know what to expect.



Not checking for null makes your code much cleaner, but it comes at a cost (depending on the complexity of the object you want to create).

Refunding Collection.emptyList()

instead null

is good practice as its cost is zero.


An existing example of an empty list returned can be seen even in Java Persistence API

the method Query#getResultList()

. It always returns an empty list of results if no search results are found.



Null is a legacy of direct memory management languages ​​where a pointer can point to nowhere. Modern languages ​​and techniques are encouraged to avoid using zeros. Generally, try using non-nullable variables where possible and consider using the option instead of using nullables. You can read more about the reasons here .

Now about your case. I guess the question was "what should I return, empty collection, empty or empty Optional?". Short answer: it depends on your use case. Using nullable result or Optional makes it clear that the entire result is optional. For example, for web browsing, it may say that you may or may not display the entire combo box. On the other hand, returning a non-null collection that may be empty means that you should always display the corresponding block, but in some cases it may not contain any elements in it.



All Articles