我使用java语言,我有一个方法,如果它被找到,应该返回一个对象。
如果没有找到,我是否应该:
返回null 抛出异常 其他
哪一个是最好的实践或习语?
我使用java语言,我有一个方法,如果它被找到,应该返回一个对象。
如果没有找到,我是否应该:
返回null 抛出异常 其他
哪一个是最好的实践或习语?
当前回答
这取决于找不到对象意味着什么。
如果是正常状态,则返回null。这只是偶尔会发生的事情,调用者应该检查它。
如果是错误,则抛出异常,调用者应决定如何处理缺少对象的错误条件。
最终,这两种方法都可以工作,尽管大多数人通常认为只有在发生异常时才使用异常是一种良好的实践。
其他回答
我同意这里的共识(如果“未找到”是一个正常的可能结果,则返回null,或者如果情况的语义要求始终找到对象,则抛出异常)。
然而,根据你的具体情况,还有第三种可能是有意义的。您的方法可以在“not found”条件下返回某种类型的默认对象,允许调用代码确保它总是接收到有效的对象,而不需要进行空检查或异常捕获。
返回null,异常就是:你的代码所做的不是预期的事情。
这取决于你的语言和代码是否支持: 三思而后行 或 EAFP(请求原谅比请求允许容易)
LBYL说你应该检查值(所以返回null) EAFP表示只需尝试操作并查看它是否失败(抛出异常)
虽然我同意以上的观点。异常应该用于异常/错误条件,在使用检查时最好返回null。
Python中的EAFP vs. LBYL: http://mail.python.org/pipermail/python-list/2003-May/205182.html (Web存档)
我更喜欢只返回null,并依赖于调用者来适当地处理它。(因为没有更好的词)例外是,如果我绝对“确定”这个方法将返回一个对象。在这种情况下,失败是一个例外,应该和应该抛出。
抛出异常的好处:
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/