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

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

返回null 抛出异常 其他

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


当前回答

我更喜欢只返回null,并依赖于调用者来适当地处理它。(因为没有更好的词)例外是,如果我绝对“确定”这个方法将返回一个对象。在这种情况下,失败是一个例外,应该和应该抛出。

其他回答

如果没有找到它是一个异常事件(即在正常情况下它应该在那里),那么就扔掉它。否则,返回一个“notfound”值(可以为空,但不一定),或者甚至让方法返回一个布尔值来表示found/notfound,并为实际对象返回一个out参数。

抛出异常的好处:

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 抛出异常 使用空对象模式 为您的方法提供一个布尔参数,以便调用者可以选择是否希望您抛出异常 提供一个额外的参数,以便调用者可以设置一个值,如果没有找到值,则返回该值

或者你可以把这些选项结合起来:

提供getter的多个重载版本,以便调用者可以决定采用哪种方式。在大多数情况下,只有第一个有搜索算法的实现,其他的只是围绕着第一个:

Object findObjectOrNull(String key);
Object findObjectOrThrow(String key) throws SomeException;
Object findObjectOrCreate(String key, SomeClass dataNeededToCreateNewObject);
Object findObjectOrDefault(String key, Object defaultReturnValue);

即使您选择只提供一个实现,您也可能希望使用这样的命名约定来阐明您的契约,并且它有助于您决定添加其他实现。

你不应该过度使用它,但它可能是有帮助的,特别是当你编写一个helper类时,你将在数百个不同的应用程序中使用许多不同的错误处理约定。

如果null从不表示错误,则返回null。

如果null始终是错误,则抛出异常。

如果null有时是一个异常,那么编写两个例程。一个例程抛出异常,另一个是布尔测试例程,它在输出参数中返回对象,如果没有找到对象,则返回false。

很难滥用Try例程。很容易忘记检查null。

所以当null是一个错误时,你只需要写

object o = FindObject();

当null不是错误时,您可以编写如下代码

if (TryFindObject(out object o)
  // Do something with o
else
  // o was not found

“其他”选项可以是让find方法接受一个带有默认对象的附加参数,如果无法找到所寻找的对象,将返回该默认对象。

否则,我只返回null,除非它确实是一个例外的情况,当对象没有找到。