我使用java语言,我有一个方法,如果它被找到,应该返回一个对象。
如果没有找到,我是否应该:
返回null 抛出异常 其他
哪一个是最好的实践或习语?
我使用java语言,我有一个方法,如果它被找到,应该返回一个对象。
如果没有找到,我是否应该:
返回null 抛出异常 其他
哪一个是最好的实践或习语?
当前回答
只有在确实是错误时才抛出异常。如果对象不存在是预期行为,则返回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)) { ...
这取决于你是否希望找到这个物体。如果你遵循学校的思想,认为exceptions应该用来表示某事,那么,嗯,呃,exceptions已经发生了:
对象发现;返回对象 没有找到对象;抛出异常
否则,返回null。
在一些函数中,我添加了一个参数:
..., bool verify = true)
True表示抛出,false表示返回错误返回值。这样,任何使用这个函数的人都有两个选项。为了方便那些忘记错误处理的人,默认值应该是true。
抛出异常的好处:
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从不表示错误,则返回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