我经常遇到某种情况可能出现问题的情况,但由于例外情况并非如此,因此使用异常是不对的。有些事情可能会出错,但它并不是一个例外
例如:
我在设计一个垄断游戏。班级有一个方法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