我使用java语言,我有一个方法,如果它被找到,应该返回一个对象。
如果没有找到,我是否应该:
返回null 抛出异常 其他
哪一个是最好的实践或习语?
我使用java语言,我有一个方法,如果它被找到,应该返回一个对象。
如果没有找到,我是否应该:
返回null 抛出异常 其他
哪一个是最好的实践或习语?
当前回答
这里还有一些建议。
如果返回一个集合,避免返回null,返回一个空集合,这使得枚举更容易处理,而不需要先进行空检查。
一些. net API使用thrownOnError参数的模式,如果对象没有找到,调用者可以选择是否真的是异常情况。类型。GetType就是一个例子。BCL的另一个常见模式是TryGet模式,其中返回一个布尔值,并通过输出参数传递值。
在某些情况下,您还可以考虑Null Object模式,它可以是默认的,也可以是没有行为的版本。关键是避免在整个代码库中进行空检查。更多信息请参见这里链接
其他回答
在一些函数中,我添加了一个参数:
..., bool verify = true)
True表示抛出,false表示返回错误返回值。这样,任何使用这个函数的人都有两个选项。为了方便那些忘记错误处理的人,默认值应该是true。
例外应该是例外。如果返回null是有效的,则返回null。
如果没有找到它是一个异常事件(即在正常情况下它应该在那里),那么就扔掉它。否则,返回一个“notfound”值(可以为空,但不一定),或者甚至让方法返回一个布尔值来表示found/notfound,并为实际对象返回一个out参数。
只提到null不被认为是异常行为的情况,我肯定是try方法,很明显,没有必要“阅读书籍”或“三思而后行”,就像这里所说的那样
所以:
bool TryFindObject(RequestParam request, out ResponseParam response)
这意味着用户的代码也将是清晰的
...
if(TryFindObject(request, out response)
{
handleSuccess(response)
}
else
{
handleFailure()
}
...
抛出异常的好处:
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/