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

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

返回null 抛出异常 其他

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


当前回答

我只是想概括一下之前提到的选项,并添加一些新的选项:

返回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类时,你将在数百个不同的应用程序中使用许多不同的错误处理约定。

其他回答

抛出异常的好处:

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/

与您正在使用的API保持一致。

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

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

返回空值而不是抛出异常,并在API文档中清楚地记录空返回值的可能性。如果调用代码不遵守API并检查空情况,它很可能会导致某种“空指针异常”:)

在c++中,我可以想到3种不同的方法来设置查找对象的方法。

选择一个

Object *findObject(Key &key);

当找不到对象时返回null。很好很简单。我选这个。下面的替代方法是为那些不讨厌out-params的人准备的。

选项B

void findObject(Key &key, Object &found);

传入一个将接收该对象的变量引用。当找不到对象时,该方法抛出异常。如果不是真的期望找不到对象,那么这种约定可能更适合——因此您可以抛出异常来表示这是一个意外情况。

C选项

bool findObject(Key &key, Object &found);

当找不到对象时,该方法返回false。与选项A相比,这个选项的优点是,您可以在一个明确的步骤中检查错误情况:

if (!findObject(myKey, myObj)) { ...

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