我使用java语言,我有一个方法,如果它被找到,应该返回一个对象。
如果没有找到,我是否应该:
返回null 抛出异常 其他
哪一个是最好的实践或习语?
我使用java语言,我有一个方法,如果它被找到,应该返回一个对象。
如果没有找到,我是否应该:
返回null 抛出异常 其他
哪一个是最好的实践或习语?
当前回答
返回null,异常就是:你的代码所做的不是预期的事情。
其他回答
我更喜欢只返回null,并依赖于调用者来适当地处理它。(因为没有更好的词)例外是,如果我绝对“确定”这个方法将返回一个对象。在这种情况下,失败是一个例外,应该和应该抛出。
例外情况与契约式设计有关。
一个对象的接口实际上是两个对象之间的契约,调用方必须满足契约,否则接收方可能会异常失败。有两种可能的契约
1)所有输入的方法都是有效的,在这种情况下,当对象没有找到时必须返回null。
2)只有某些输入是有效的,即导致找到对象的输入。在这种情况下,您必须提供第二个方法,允许调用者确定其输入是否正确。例如
is_present(key)
find(key) throws Exception
当且仅当你提供了第二个契约的两个方法,你被允许抛出异常,但什么都没有发现!
或者返回一个Option
选项基本上是一个容器类,它强制客户端处理展位案例。Scala有这个概念,查查它的API。
然后你在这个对象上有T getOrElse(T valueIfNull)这样的方法,它们要么返回找到的对象,要么返回客户端指定的替代对象。
抛出异常的好处:
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/
如果方法返回一个集合,则返回一个空集合(如上所述)。但请不要收钱。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或其他语言中)!所以不要返回在编译时没有检查的空值。