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()...