返回 true 或 false 或抛出异常

ant*_*009 2 java optimization

java version "1.7.0_75"
Run Code Online (Sandbox Code Playgroud)

你好,

只是想知道比较以下 2 个函数的首选最佳实践是什么。

第一个抛出应该在调用函数中捕获的 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;
}
Run Code Online (Sandbox Code Playgroud)

只需返回真或假:

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;
}
Run Code Online (Sandbox Code Playgroud)

通常在过去,我总是通过返回 true 或 false 来选择第二个。但现在我只是在寻找替代解决方案。

非常感谢您的任何建议,

alf*_*sin 5

如果您编写其他开发人员将使用的 API - 最好采用第二种方法,从“客户”方面处理会更容易(也更干净):

while (!disconnected()) {
    // do something else
    // sleep and try again
    // etc
}
Run Code Online (Sandbox Code Playgroud)

一般来说 - 不要抛出您知道如何优雅处理的异常!