我使用java语言,我有一个方法,如果它被找到,应该返回一个对象。
如果没有找到,我是否应该:
返回null 抛出异常 其他
哪一个是最好的实践或习语?
我使用java语言,我有一个方法,如果它被找到,应该返回一个对象。
如果没有找到,我是否应该:
返回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/
这取决于你的方法。如果你的方法应该总是返回一个有效的对象,但却没有找到,那么抛出异常就是正确的方法。如果该方法只是返回一个可能存在也可能不存在的对象(比如联系人的图像),则不应该引发错误。
你可能还想公开一个返回布尔值true/false的方法,如果这个方法实际上会返回一个对象,这样你就不必a)检查null或b)捕捉异常
我更喜欢只返回null,并依赖于调用者来适当地处理它。(因为没有更好的词)例外是,如果我绝对“确定”这个方法将返回一个对象。在这种情况下,失败是一个例外,应该和应该抛出。
与您正在使用的API保持一致。
通常它应该返回null。调用该方法的代码应该决定是抛出异常还是尝试其他操作。