我使用java语言,我有一个方法,如果它被找到,应该返回一个对象。
如果没有找到,我是否应该:
返回null 抛出异常 其他
哪一个是最好的实践或习语?
我使用java语言,我有一个方法,如果它被找到,应该返回一个对象。
如果没有找到,我是否应该:
返回null 抛出异常 其他
哪一个是最好的实践或习语?
当前回答
这里还有一些建议。
如果返回一个集合,避免返回null,返回一个空集合,这使得枚举更容易处理,而不需要先进行空检查。
一些. net API使用thrownOnError参数的模式,如果对象没有找到,调用者可以选择是否真的是异常情况。类型。GetType就是一个例子。BCL的另一个常见模式是TryGet模式,其中返回一个布尔值,并通过输出参数传递值。
在某些情况下,您还可以考虑Null Object模式,它可以是默认的,也可以是没有行为的版本。关键是避免在整个代码库中进行空检查。更多信息请参见这里链接
其他回答
返回null,异常就是:你的代码所做的不是预期的事情。
作为一般规则,如果方法应该总是返回一个对象,那么就使用例外。如果您预期偶尔会出现null,并希望以某种方式处理它,那么就使用null。
无论你做什么,我强烈建议反对第三种选择:返回一个字符串,说“WTF”。
这取决于找不到对象意味着什么。
如果是正常状态,则返回null。这只是偶尔会发生的事情,调用者应该检查它。
如果是错误,则抛出异常,调用者应决定如何处理缺少对象的错误条件。
最终,这两种方法都可以工作,尽管大多数人通常认为只有在发生异常时才使用异常是一种良好的实践。
如果方法返回一个集合,则返回一个空集合(如上所述)。但请不要收钱。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。