我使用java语言,我有一个方法,如果它被找到,应该返回一个对象。

如果没有找到,我是否应该:

返回null 抛出异常 其他

哪一个是最好的实践或习语?


当前回答

抛出异常的好处:

Cleaner control flow in your calling code. Checking for null injects a conditional branch which is natively handled by try/catch. Checking for null doesn't indicate what it is you're checking for - are you checking for null because you're looking for an error you're expecting, or are you checking for null so you don't pass it further on downchain? Removes ambiguity of what "null" means. Is null representative of an error or is null what is actually stored in the value? Hard to say when you only have one thing to base that determination off of. Improved consistency between method behavior in an application. Exceptions are typically exposed in method signatures, so you're more able to understand what edge cases the methods in an application account for, and what information your application can react to in a predictable manner.

有关更多示例的解释,请参见:http://metatations.com/2011/11/17/returning-null-vs-throwing-an-exception/

其他回答

“其他”选项可以是让find方法接受一个带有默认对象的附加参数,如果无法找到所寻找的对象,将返回该默认对象。

否则,我只返回null,除非它确实是一个例外的情况,当对象没有找到。

这取决于方法的性质以及如何使用它。如果正常情况下可能找不到对象,则返回null。如果总是找到对象是正常行为,则抛出异常。

根据经验,只在发生异常时使用异常。不要在编写代码时将异常抛出和捕获作为其正常操作的一部分。

首选返回null——

如果调用者在不检查的情况下使用它,异常就会在那里发生。

如果调用者并没有真正使用它,不要给他一个try/catch块

在数据层代码中,我有时使用以下代码,允许调用者决定“对象未找到”是否意味着发生了错误。


DataType GetObject(DBConnection conn, string id, bool throwOnNotFound) {
    DataType retval = ... // find object in database
    if (retval != null || ! throwOnNotFound) {
        return retval;
    } else {
        throw new NoRowsFoundException("DataType object with id {id} not found in database");
    }
}

DataType GetObject(DBConnection conn, string id) {
    return GetObject(conn, id, true);
} 

与您正在使用的API保持一致。