Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives to returning NULL

   /**      * Returns the foo with the matching id in this list      *       * @param id the id of the foo to return      * @return the foo with the matching id in this list      */     public Foo getFoo(int id)     {         for (Foo foo : list)         {             if (foo.getID() == id)             {                 return foo;             }         }          return null;     } 

Instead of returning null when foo is not found, should I throw an exception? Does it matter, and is there a "best practices" idiom on the subject? By the way, I know my example is a bit contrived, but I hope you get the idea...

Thanks.

EDIT

Changed code to get Foo based on id to better illustrate a real-world scenario.

like image 490
mre Avatar asked May 12 '11 16:05

mre


People also ask

What can I do instead of return null?

Another way to avoid returning null is to use a Null object design pattern. A null object is an object without behavior like a stub that a developer can return to the caller instead of returning null value. The caller doesn't need to check the order for null value because a real but empty Order object is returned.

What can I use instead of null in Java?

Throwing an exception is another common alternative in the Java API to returning a null when, for any reason, a value can't be provided. A typical example of this is the conversion of String into an int , provided by the Integer.

Is it good practice to return null?

Returning null Creates More Work A function that returns a null reference achieves neither goal. Returning null is like throwing a time bomb into the software. Other code must a guard against null with if and else statements. These extra statements add more complexity to the software.

Is it better to return null or empty string?

Returning null is usually the best idea if you intend to indicate that no data is available. An empty object implies data has been returned, whereas returning null clearly indicates that nothing has been returned.


1 Answers

Returning null is not only more simple to handle, performs better too. The exceptions must be used to handle exceptional cases.

like image 180
Ronye Vernaes Avatar answered Sep 18 '22 15:09

Ronye Vernaes