Java 8 has introduced Optional
API to denote values which could be null
at runtime. In the following cases is it best to throw a checked exception or return a Optional
return type to represent edge case?
Case 1: Returning type Optional
private Optional<Item> getItem(String itemName)
{
for (Item item : items)
{
if (item.getName().equals(itemName))
return Optional.of(item);
}
return Optional.empty();
}
Case 2: Throwing checked exception
private Item getItem(String itemName) throws ItemNotFound
{
for (Item item : items)
{
if (item.getName().equals(itemName))
return item;
}
throw new ItemNotFound();
}
As Martin Fowler advocates, Optional
/Special case pattern is a better practice but in this simple scenario throwing a checked exception does the job too.
Which one should I be following?
This basically boils down to: Does it make sense for this use-case for item to be missing?
Lets say say an app has users. User can add a phone number to his account info. As his prone number does not have to be there, you can use optional. Phone number might be there but might be missing. Client code has to handle Optional/nullable value.
On the other hand if I want to look at his email, which is a mandatory during registration. Then the exception is the way to go. Email must be there, but is not. Here client code faces invalid application state/corrupted user.
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