Reputation: 2734
I don't understand the best practices about when a method should throw an exception or return an error code / boolean
result.
Specifically, I have this situation: There is a thread that is polling a device (retrieving its status) every 30 seconds.
If the device is not reachable, the application must not stop, since it does not need to be able to communicate with the mentioned device to perform all the other operations it does.
So, in general, the thread code is like the following:
while(true)
{
device.connect();
string st = device.getStatus();
updateStatus(st);
device.disconnect();
sleep(30);
}
Currently, the connect()
method throws an exception if the device is not online.
I think that, in this situation, maybe it is a better practice to make the connect()
method to return a boolean result in order to report whether or not the device is reachable, but I am not sure at all.
The above would look like this:
while(true)
{
if(device.connect())
{
string st = device.getStatus();
device.disconnect();
updateStatus(st);
}
sleep(30);
}
Actually, when the application is in production, the device "should" be always online, that makes me think the best option is an exception.
On the other hand, the application can keep the execution perfectly without communciating with the device. The only consequence of it not being connected is that the functionallity associated to it is disabled. This is what makes me think that the boolean
return value is better.
If the device is not connected, I will have a thread throwing an exception every 30 seconds. Even if the exception is catched, is this admissible in terms of software engineering good practices?
Upvotes: 0
Views: 123
Reputation: 2535
As per the thread linked to in the comment on the original question, exceptions do give you the ability to provide more detail on the actual failure. In this context, a boolean might be restrictive - what if the device is not attached, or what it is attached but not responding? An exception can clearly indicate both of those conditions, while a boolean cannot.
Boolean values, in my view, work well when the application has two possible outcomes where it can still function 'normally' - such as validation. If, for example, your app needs to validate an email address and a user enters an invalid email address, that's okay - the app can continue normally and just prompt the user to fix the validation errors.
However, in the event that something interferes with normal execution of the application, such as a device being inaccessible, I would go with an exception. It is, after all, an exceptional condition. For what it's worth, if I were coding this in a language like Java, I would use a checked exception since it's something that the application can reasonably be expected to recover from.
Upvotes: 1