I come to an API getStock designed, where I have no good judgment, on how I should deal with failure of operation.
The API will enable me to pass a stock code, and return a stock if success.
Shall I use null returned value to indicate failure of operation, or throwing checked exception to indicate failure of operation? Or possible Null Object Pattern? Why?
Null Returned Value
// User force to check the returned value each time.
// This happen when, stock server is down, network is down,
// stockCode is not valid...
Stock stock = stockServer.getStock(stockCode);
if (stock != null) {
// Success.
}
Checked Exception
try {
// User force to catch the exception each time.
// This happen when, stock server is down, network is down,
// stockCode is not valid...
Stock stock = stockServer.getStock(stockCode);
// Success.
} catch (StockNotFoundException ex) {
}
Null Object Pattern
Stock stock = stockServer.getStock(stockCode);
// stock.getPrice(), stock.getVolume() will return 0...
// But when there is a need to check whether we are getting
// a null stock, we need to check
// if (stock.getPrice() == 0.0 && stock.getVolume()...
My advice when it comes to this sort of (subjective) design decision is to go with the grain of the language (i.e. try and follow the practices used by the standard library of the language.) The Java standard library usually prefers exceptions for error handling, rather than return values. For example, the Java
Socketclass throws anIOExceptionif it cannot connect (e.g. if the network is down, or the remote address is invalid).Null return values, on the other hand, are usually used in cases where, for example, a Collection object is unable to find a specified key.
So I think, in your case, an exception is more “in the spirit” of the Java language, because it could indicate a serious problem such as a network error.
You could also use a
nullreturn value to indicate that the specifiedstockCodedoes not exist, and an Exception to indicate a more serious problem, such as a down network. Although, this will require users of your API to check for a null return value and handle the exception.