我使用java语言,我有一个方法,如果它被找到,应该返回一个对象。
如果没有找到,我是否应该:
返回null 抛出异常 其他
哪一个是最好的实践或习语?
我使用java语言,我有一个方法,如果它被找到,应该返回一个对象。
如果没有找到,我是否应该:
返回null 抛出异常 其他
哪一个是最好的实践或习语?
当前回答
只提到null不被认为是异常行为的情况,我肯定是try方法,很明显,没有必要“阅读书籍”或“三思而后行”,就像这里所说的那样
所以:
bool TryFindObject(RequestParam request, out ResponseParam response)
这意味着用户的代码也将是清晰的
...
if(TryFindObject(request, out response)
{
handleSuccess(response)
}
else
{
handleFailure()
}
...
其他回答
在数据层代码中,我有时使用以下代码,允许调用者决定“对象未找到”是否意味着发生了错误。
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);
}
这取决于你是否希望找到这个物体。如果你遵循学校的思想,认为exceptions应该用来表示某事,那么,嗯,呃,exceptions已经发生了:
对象发现;返回对象 没有找到对象;抛出异常
否则,返回null。
这取决于你的方法。如果你的方法应该总是返回一个有效的对象,但却没有找到,那么抛出异常就是正确的方法。如果该方法只是返回一个可能存在也可能不存在的对象(比如联系人的图像),则不应该引发错误。
你可能还想公开一个返回布尔值true/false的方法,如果这个方法实际上会返回一个对象,这样你就不必a)检查null或b)捕捉异常
如果没有找到它是一个异常事件(即在正常情况下它应该在那里),那么就扔掉它。否则,返回一个“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/