java - Is it right to create a new object to avoid a null pointer exception? -


i don't want pass null value view tier, if like:

  public list<object> getlistobjfoo(){     list<object> listobj = datasource.getall();     return listobj != null ? listobj : new arraylist<object>();   } 

it should considered or bad practice? , use of "optional" in "guava" google better doing this? why?

your code bad practice because allocates new instance. try use collection.emptylist() instead.

drawback: if consumer of code wants change list, need make copy of list. practice since many frameworks return immutable lists , consumer, can never sure unless api says allowed result.

returning null bad because exports implementation detail of code consumer. or put way around: if change implementation , find want return null, need add checks in places api used. hampers ability evolve code , api.

for other (non-collection) types, should @ "optional" pattern described here: https://stackoverflow.com/a/16218718/34088

this pattern allows tell consumers of api method might return "nothing" without ever returning null. way, consumers know expect.


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -