我使用java语言,我有一个方法,如果它被找到,应该返回一个对象。

如果没有找到,我是否应该:

返回null 抛出异常 其他

哪一个是最好的实践或习语?


当前回答

例外应该是例外。如果返回null是有效的,则返回null。

其他回答

通常它应该返回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/

这里还有一些建议。

如果返回一个集合,避免返回null,返回一个空集合,这使得枚举更容易处理,而不需要先进行空检查。

一些. net API使用thrownOnError参数的模式,如果对象没有找到,调用者可以选择是否真的是异常情况。类型。GetType就是一个例子。BCL的另一个常见模式是TryGet模式,其中返回一个布尔值,并通过输出参数传递值。

在某些情况下,您还可以考虑Null Object模式,它可以是默认的,也可以是没有行为的版本。关键是避免在整个代码库中进行空检查。更多信息请参见这里链接

只有在确实是错误时才抛出异常。如果对象不存在是预期行为,则返回null。

否则就是个人喜好的问题了。

或者返回一个Option

选项基本上是一个容器类,它强制客户端处理展位案例。Scala有这个概念,查查它的API。

然后你在这个对象上有T getOrElse(T valueIfNull)这样的方法,它们要么返回找到的对象,要么返回客户端指定的替代对象。