我正在开发一款安卓服务,并遇到两种不同的编写代码来处理验证的方法。
第一种方法:使用布尔值或明确检查。在这种方法中,我返回从函数获取到的任何值。返回的值可以是null,也可能是Closed(无效)。
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
第二种风格: 使用异常处理。在这里,如果会话关闭(无效)或位置为空,我从实用方法中抛出自定义异常。并按以下方式处理:
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
在我看来,第一种方法更好,原因如下:
- 在第二种方法中,抛出异常会导致性能损失。
使用第一种方法是否可以,还是使用第二种方法有一些真正的好处?