某个函数返回一个特定的代码,用来表示某种错误情况
public int withdraw(int amount) {
if (amount > balance) {
return -1;
} else {
balance -= amount;
return 0;
}
}
重构:改用异常
public int withdraw(int amount) {
if (amount > balance) {
throw new BalanceException("余额不足。");
}
balance -= amount;
}