Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice: Using Java 8 Optional or throwing Exception

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?

like image 702
Vino Avatar asked Jan 26 '23 18:01

Vino


1 Answers

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.

like image 145
Januson Avatar answered Jan 29 '23 08:01

Januson