java version "1.7.0_75"
你好,
只是想知道比较下面两个函数的首选最佳实践是什么.
第一个抛出应该在调用函数中捕获的NullPointerException.
如果存在空指针异常,则第二个返回false.
抛出异常:
public void disconnect() throws NullPointerException {
if(mClientConnection == null) {
throw new NullPointerException("mClientConnection has an invalid reference");
}
if(mClientConnection.isConnected()) {
mClientConnection.disconnect();
}
mClientConnection = null;
}
只返回true或false:
public boolean disconnect() {
if(mClientConnection == null) {
log.log(Level.SEVERE, "Cannot disconnect as mClientConnection is null");
return false;
}
if(mClientConnection.isConnected()) {
mClientConnection.disconnect();
}
mClientConnection = null;
return true;
}
通常在过去,我总是选择第二个,只返回true或false.但现在我只是在寻找替代解决方案.
非常感谢任何建议,
解决方法:
如果您编写其他开发人员将使用的API – 更好地采用第二种方法,从“客户”方面处理起来更容易(也更清晰):
while (!disconnected()) {
// do something else
// sleep and try again
// etc
}
一般情况下 – 不要抛出你知道如何优雅处理的异常!
标签:java,optimization
来源: https://codeday.me/bug/20191008/1873510.html