Best Practice: Using Java 8 Optional or throwing Exception

Vino :

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?

Januson :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=87643&siteId=1
Recommended