/**
* 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