What is the preferred design for methods that encounter predictable but unpreventable failure? Should they return an empty result or throw an exception on failure? Please explain your reasoning.
I'll give two sample methods:
- A method like Arrays.binarySearch() that returns the index of a value within an array.
Tickets.buy(20, 100)
. A ticket bot attempts to buy at least 20 tickets using $100. The method returns the list of tickets that were bought.
For both methods, let us assume that the user has no way of predicting whether the method will succeed in finding a match.
Method 1 can fail if:
- The array does not contain the desired value.
Method 2 can fail if:
- There aren't enough tickets.
- There are enough tickets for sale, but they cost more than $100.
Java chose to return the equivalent to an empty result for method 1, but doing the same for method 2 wouldn't allow you to differentiate between the two kinds of errors. What are the guidelines for choosing between the two possible designs?
Please note that although this question contains two concrete methods, I am looking for general design guidelines not a specific solution to the aforementioned methods.