我經常遇到某種情況可能出現問題的情況,但由於例外情況並非如此,因此使用異常是不對的。有些事情可能會出錯,但它並不是一個例外
例如:
我在設計一個壟斷遊戲。班級有一個方法buyHouse和一個計算剩餘房屋數量的字段(有32個房屋在壟斷中)。有可能出錯的是一個玩家在剩下0時買房子。我應該如何處理這個問題。這是我能想出的3種方法。
1. public void buyHouse(Player player, PropertyValue propertyValue)
{
if(houseCount < 0) throw new someException;
....
//Not really an exceptional situation
}
2. public boolean buyHouse(Player player, PropertyValue propertyValue)
{
if(houseCount < 0) return false;
....
//This I think is the most normal approach but changing something
//and returning if it was a success seems bad practice to me.
}
3. public boolean housesLeft()
{
if(houseCount > 0) return true;
return false;
//Introducing a new method. But now I expect the client to call this method
//first before calling buyHouse().
}
你會怎麼做?
而不是如果(東西是真的)返回true;返回false;我寧願做最後的布爾retVal; retVal = houseCount> 0;返回(retVal); – TofuBeer 2010-07-15 19:28:49