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

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

返回null 抛出异常 其他

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


当前回答

不幸的是,JDK是不一致的,如果你试图访问资源包中不存在的键,你会得到not found异常,当你从map请求值时,如果它不存在,你会得到null。因此,我将获胜者答案更改为以下内容,如果找到的值可以为null,则在未找到时引发异常,否则返回null。所以遵循规则,只有一个例外,如果你需要知道为什么没有找到值,那么总是抛出异常,或者。

其他回答

或者返回一个Option

选项基本上是一个容器类,它强制客户端处理展位案例。Scala有这个概念,查查它的API。

然后你在这个对象上有T getOrElse(T valueIfNull)这样的方法,它们要么返回找到的对象,要么返回客户端指定的替代对象。

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


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文档中清楚地记录空返回值的可能性。如果调用代码不遵守API并检查空情况,它很可能会导致某种“空指针异常”:)

在c++中,我可以想到3种不同的方法来设置查找对象的方法。

选择一个

Object *findObject(Key &key);

当找不到对象时返回null。很好很简单。我选这个。下面的替代方法是为那些不讨厌out-params的人准备的。

选项B

void findObject(Key &key, Object &found);

传入一个将接收该对象的变量引用。当找不到对象时,该方法抛出异常。如果不是真的期望找不到对象,那么这种约定可能更适合——因此您可以抛出异常来表示这是一个意外情况。

C选项

bool findObject(Key &key, Object &found);

当找不到对象时,该方法返回false。与选项A相比,这个选项的优点是,您可以在一个明确的步骤中检查错误情况:

if (!findObject(myKey, myObj)) { ...

如果方法返回一个集合,则返回一个空集合(如上所述)。但请不要收钱。EMPTY_LIST或类似的!(以Java为例)

如果该方法检索单个对象,则您有一些选项。

If the method should always find the result and it's a real exception case not to find the object, then you should throw an exception (in Java: please an unchecked Exception) (Java only) If you can tolerate that the method throws a checked exception, throw a project specific ObjectNotFoundException or the like. In this case the compiler says you if you forget to handle the exception. (This is my preferred handling of not found things in Java.) If you say it's really ok, if the object is not found and your Method name is like findBookForAuthorOrReturnNull(..), then you can return null. In this case it is strongly recomminded to use some sort of static check or compiler check, wich prevents dereferencing of the result without a null check. In case of Java it can be eg. FindBugs (see DefaultAnnotation at http://findbugs.sourceforge.net/manual/annotations.html) or IntelliJ-Checking.

如果决定返回null,请小心。如果你不是项目中唯一的程序员,你会在运行时得到nullpointerexception(在Java或其他语言中)!所以不要返回在编译时没有检查的空值。

这取决于你的方法。如果你的方法应该总是返回一个有效的对象,但却没有找到,那么抛出异常就是正确的方法。如果该方法只是返回一个可能存在也可能不存在的对象(比如联系人的图像),则不应该引发错误。

你可能还想公开一个返回布尔值true/false的方法,如果这个方法实际上会返回一个对象,这样你就不必a)检查null或b)捕捉异常