/** * 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.
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.
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.
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.
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.
Returning null
is not only more simple to handle, performs better too. The exceptions must be used to handle exceptional cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With