I'm reading J. Bloch's effective Java and now I'm at the section about avoiding returning nulls, but returning empty collections. This's the code example form the section:
// The right way to return a copy of a collection
public List<Cheese> getCheeseList() {
if (cheesesInStock.isEmpty())
return Collections.emptyList(); // Always returns same list
else
return new ArrayList<Cheese>(cheesesInStock);
}
I really cannot understand what's wrong with just returning the cheesesInStock if cheesesInStock.isEmpty(). why is it better to return the predefined Collections.emptyList(). What kind of troubles we may get into, if we return cheesesInStock instead.
If the method returns cheesesInStock - the caller may add some cheese to the list.
It is a bad practice as you may want to control adding procedure.
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