重构第十章
14.Replace Error Code With Exception(以异常取代错误码)
某个函数返回一个特定的代码,用以表示某种错误情况,改用异常。
Example:
class Account...
int withdraw(int amount) {
if(amount > _balance) {
return -1;
} else {
_balance = amount ;
return 0;
}
}
private int _balance;
End:
class Account...
void withdraw(int amount) {
Assert.isTrue("sufficient funds", amount <= _balance);
_balance = amount
}
class Assert...
static void isTrue(String comment, boolean test) {
if(!test) {
throw new RuntimeException("Assertion failed:" + comment);
}
}
Conclusion:
程序中发现错误的地方,需要让调用者知道这个错误,可以使用异常来清楚地将[普通程序]和[错误处理]分开。这使得程序更加容易理解。
注意
重构必须在有单元测试的情况下,保证之前的功能修改后不收影响。切记!!!
网友评论