我使用java语言,我有一个方法,如果它被找到,应该返回一个对象。
如果没有找到,我是否应该:
返回null 抛出异常 其他
哪一个是最好的实践或习语?
我使用java语言,我有一个方法,如果它被找到,应该返回一个对象。
如果没有找到,我是否应该:
返回null 抛出异常 其他
哪一个是最好的实践或习语?
当前回答
在一些函数中,我添加了一个参数:
..., bool verify = true)
True表示抛出,false表示返回错误返回值。这样,任何使用这个函数的人都有两个选项。为了方便那些忘记错误处理的人,默认值应该是true。
其他回答
我同意这里的共识(如果“未找到”是一个正常的可能结果,则返回null,或者如果情况的语义要求始终找到对象,则抛出异常)。
然而,根据你的具体情况,还有第三种可能是有意义的。您的方法可以在“not found”条件下返回某种类型的默认对象,允许调用代码确保它总是接收到有效的对象,而不需要进行空检查或异常捕获。
抛出异常的好处:
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文档中清楚地记录空返回值的可能性。如果调用代码不遵守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)) { ...
在数据层代码中,我有时使用以下代码,允许调用者决定“对象未找到”是否意味着发生了错误。
DataType GetObject(DBConnection conn, string id, bool throwOnNotFound) {
DataType retval = ... // find object in database
if (retval != null || ! throwOnNotFound) {
return retval;
} else {
throw new NoRowsFoundException("DataType object with id {id} not found in database");
}
}
DataType GetObject(DBConnection conn, string id) {
return GetObject(conn, id, true);
}