I am developing an android service and coming across two different styles to write code to handle validations.
First Style: Using boolean or explicit checks. In this method, I return the whatever values I get from functions. Returned values could be null, Closed (not valid).
boolean fbConnected = appPrefences.isFBConnected();
if (!fbConnected)
{
ShowNotification("FB not connected");
stopSelf();
return;
}
Session session = GetSession();
if (session.isClosed())
{
ShowNotification("Session not valid");
stopSelf();
return;
}
Coordinates result = getLocation();
if(result == null)
{
ShowNotification("Could not get location");
stopSelf();
return;
}
// Do something finally with Session, FB and location
Second Style: Using Exception handling. Here, I throw my own custom exception from utility methods if the session is closed (invalid) or if the location is null. And I handle it as follows:
try
{
appPrefences.connectToFb();
Session session = GetSession();
Coordinates result = getLocation();
}
catch(FBException e)
{
ShowNotification("FB not connected");
stopSelf();
return;
}
catch(SessionException e)
{
ShowNotification("Session not valid");
stopSelf();
return;
}
catch(LocationException e)
{
ShowNotification("Could not get location");
stopSelf();
return;
}
// Do something finally with Session, FB and location
In my view the first one is better, for the reason below:
Is it OK to use the first method or there are some real benefits to use the second method ?
Use exceptions to
signal that the caller violates the preconditions for calling the function. This should usually lead to a fix in the programm, because it is the responsibility of the caller to ensure that the preconditions are met.
signal that the postconditions cannot be ensured by the function despite the fact that the preconditions for calling the function are fulfilled. This should be handled gracefully by the caller.
I think a function like isFBConnected should check whether facebook is connected. There are two perfectly valid answers: Yes, No. An exception should be thrown if the function is not able to determine whether facebook is connected.
The use of try/catch blocks in normal program flow incurs a performance hit. It's better to use the if/then statements in the first example.
https://softwareengineering.stackexchange.com/questions/189222/are-exceptions-as-control-flow-considered-a-serious-antipattern-if-so-why
This is mentioned in Effective Java. Exceptions are, as their name implies, to be used only for exceptional conditions; they should never be used for ordinary control flow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With