/**
* 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;
}
而不是返回null
如果找不到foo
,我应该throw
的exception
?这有什么关系,并且有关于这个问题的“最佳实践”成语吗?顺便说一句,我知道我的例子有点做作,但我希望你能明白...替代返回NULL
谢谢。
编辑
更改代码来获得Foo
基于ID为了更好地说明一个真实世界的场景。
在某处有一个关于语言设计者的评论,他说他希望自己从不介绍null值。我不记得他的理由是什么。 – 2011-05-12 16:41:07
@James P:那是CAR Hoare,这是一个报价:http://lambda-the-ultimate.org/node/3186 – 2011-05-12 17:59:47
你可以使用NULL OBJECT PATTERN。检查是否符合您的要求http://en.wikipedia.org/wiki/Null_Object_pattern 警告... 应认真使用此模式,因为它可以使错误/错误显示为正常程序执行。[5] – 2011-05-13 09:25:02