mre*_*mre 25 java null design-patterns return-value
/**
* Returns the foo with the matching id in this list
*
* @param id the id of the foo to return
* @return the foo with the matching id in this list
*/
public Foo getFoo(int id)
{
for (Foo foo : list)
{
if (foo.getID() == id)
{
return foo;
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
而不是返回的null时候foo没有发现,我应该throw的exception?这是否重要,是否有关于这个问题的"最佳实践"成语?顺便说一下,我知道我的例子有点做作,但我希望你明白这个想法......
谢谢.
编辑
更改了Foo基于id的代码,以更好地说明真实场景.
Ron*_*aes 20
返回null不仅更容易处理,也表现更好.必须使用例外来处理特殊情况.
st.*_*ver 11
我会说这取决于你的方法的语义.
将foo在列表中几乎总是发现了什么?(例如,如果它是一个包含有限数量对象的缓存).如果是这样,那么找不到可能意味着出现了问题 - 例如,某些应用程序初始化失败,或者密钥无效 - 并且异常可能是合理的.
然而,在大多数情况下,我会回来null.也许客户端知道对象可能不存在并且具有编码逻辑来处理该情况; 如果您使用了异常,则该代码将更难以阅读,理解和维护.
一些API实际上提供了两个方法:一个find可能返回null方法,以及get或load抛出异常的方法.
嗯...当有疑问时,错误地支持null :)
null如果将其记录为有效结果,则返回是正常的.
另一种选择是空对象模式.那是 - 它的一个实例Foo没有任何数据:
public class Foo {
public static final Foo NULL_FOO = new Foo();
}
Run Code Online (Sandbox Code Playgroud)
并返回它.
| 归档时间: |
|
| 查看次数: |
4081 次 |
| 最近记录: |