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

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

返回null 抛出异常 其他

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


当前回答

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


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);
} 

其他回答

它不包含对象可能发生在正常操作期间,应该由调用者返回NULL来处理。

如果不包含对象表明调用代码或内部状态存在错误,则执行断言。

如果不包含该对象,则表示不经常发生事件。(就像有人从商店中删除了一件商品,而你同时还在结账。)然后抛出异常。

例外应该是例外。如果返回null是有效的,则返回null。

如果null从不表示错误,则返回null。

如果null始终是错误,则抛出异常。

如果null有时是一个异常,那么编写两个例程。一个例程抛出异常,另一个是布尔测试例程,它在输出参数中返回对象,如果没有找到对象,则返回false。

很难滥用Try例程。很容易忘记检查null。

所以当null是一个错误时,你只需要写

object o = FindObject();

当null不是错误时,您可以编写如下代码

if (TryFindObject(out object o)
  // Do something with o
else
  // o was not found

如果方法返回一个集合,则返回一个空集合(如上所述)。但请不要收钱。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或其他语言中)!所以不要返回在编译时没有检查的空值。

这取决于你是否希望找到这个物体。如果你遵循学校的思想,认为exceptions应该用来表示某事,那么,嗯,呃,exceptions已经发生了:

对象发现;返回对象 没有找到对象;抛出异常

否则,返回null。