Spiga

一天一个重构方法(19):以异常代替错误码

2009-07-25 20:25:00

Replace Error Code with Exception:以异常代替错误码

某个函数返回一个特定的代码,用以表示某种错误情况,请改用异常。

public int Withdraw(int amount)
{
	if (amount > _balance)
		return -1;
	else
	{
		_balance -= amount;
		return 0;
	}
}

改成异常后的代码

public void Withdraw(int amount)
{
	if (amount > _balance)
		throw new Exception();

	 _balance -= amount;
}

异常,这种方式之所以更好,因为它清楚地将普通程序和错误处理分开了,这使得程序更容易理解。我坚信:代码的可理解性应该是我们追求的目标。