我使用java语言,我有一个方法,如果它被找到,应该返回一个对象。
如果没有找到,我是否应该:
返回null 抛出异常 其他
哪一个是最好的实践或习语?
我使用java语言,我有一个方法,如果它被找到,应该返回一个对象。
如果没有找到,我是否应该:
返回null 抛出异常 其他
哪一个是最好的实践或习语?
当前回答
例外应该是例外。如果返回null是有效的,则返回null。
其他回答
这取决于方法的性质以及如何使用它。如果正常情况下可能找不到对象,则返回null。如果总是找到对象是正常行为,则抛出异常。
根据经验,只在发生异常时使用异常。不要在编写代码时将异常抛出和捕获作为其正常操作的一部分。
这取决于你的语言和代码是否支持: 三思而后行 或 EAFP(请求原谅比请求允许容易)
LBYL说你应该检查值(所以返回null) EAFP表示只需尝试操作并查看它是否失败(抛出异常)
虽然我同意以上的观点。异常应该用于异常/错误条件,在使用检查时最好返回null。
Python中的EAFP vs. LBYL: http://mail.python.org/pipermail/python-list/2003-May/205182.html (Web存档)
如果方法返回一个集合,则返回一个空集合(如上所述)。但请不要收钱。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或其他语言中)!所以不要返回在编译时没有检查的空值。
只有在确实是错误时才抛出异常。如果对象不存在是预期行为,则返回null。
否则就是个人喜好的问题了。
只提到null不被认为是异常行为的情况,我肯定是try方法,很明显,没有必要“阅读书籍”或“三思而后行”,就像这里所说的那样
所以:
bool TryFindObject(RequestParam request, out ResponseParam response)
这意味着用户的代码也将是清晰的
...
if(TryFindObject(request, out response)
{
handleSuccess(response)
}
else
{
handleFailure()
}
...