java - Why is it considered good practice to return an empty collection? -


i have read several books , seen several blogs discussing how returning empty collection better returning null. understand trying avoid check, don't understand why returning empty collection better returning null. example:

public class dog{     private list<string> bone;     public list<string> get(){        return bone;    }  } 

vs

 public class dog{     private list<string> bone;     public list<string> get(){        if(bone == null){         return collections.emptylist();        }        return bone;    }  } 

example 1 throw nullpointerexception , example 2 throw unsupportedoperation exception, both generic exceptions. makes 1 better or worse other?

also third option this:

 public class dog{     private list<string> bone;     public list<string> get(){        if(bone == null){         return new arraylist<string>();        }        return bone;    }  } 

but problem you're adding unexpected behavior code others may have maintain.

i'm looking solution predicament. many people on blogs tend better without detailed explanation why. if returning immutable list best practice ok doing it, understand why better.

if return empty collection (but not necessarily collections.emptylist()), avoid surprising downstream consumers of method unintentional npe.

this preferable returning null because:

  • the consumer doesn't have guard against it
  • the consumer can operate on collection irrespective of how many elements in it

i not collections.emptylist() since, point out, you're trading 1 runtime exception in adding list unsupported , once again surprise consumer.

the ideal solution this: eager initialization of field.

private list<string> bone = new arraylist<>(); 

the next solution this: make return optional , in case doesn't exist. instead of throwing provide empty collection here if desired.

dog dog = new dog(); dog.get().orelsethrow(new illegalstateexception("dog has no bones??")); 

Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -