Re: [問題] 程式的例外
亂入一下。
看見很多討論 (甚至 OP) 把
try {
doSomething();
doAnotherThing();
} catch (NoDataForSomethingException e) {
// do something
} catch (NoDataForAnotherThingException e) {
// do handlng
}
跟
if (hasDataForSomething()) {
if (hasDataForAnotherThing()) {
doSomething();
doAnotherThing();
}
}
作比較。
其實這樣比較有點偏頗。Exception 的用意是回報給 caller 有問題
發生,所以應該比較的是回報問題的機制。是不是可以事前檢查來迴避
問題是另一範籌的事。
所以應該比較的是:
try {
doSomething();
doAnotherThing();
} catch (NoDataForSomethngException e) {
// handling
} catch (NoDataForAnotherThingException e) {
//handling
}
和
int result = doSomething();
if (result == NO_DATA_FOR_SOMETHING) {
// handling
}
if (result == OK) {
result = doAnotherThing();
}
if (result== NO_DATA_FOR_ANOTHER_THING) {
//handling
}
首先要明白的是:事前檢查並不能取代問題回報。
常用的問題回報機制有上面提到的兩種(應該還有其他):
Exception 跟 回傳結果
孰優孰劣其實難以一概而論。
Exception 最大的優點是你能把 Normal flow 寫好,別人
讀起 code 來的時候,就能知道正常的運作該長怎樣 (上面的
例子就是先 doSomething() 再 doAnotherThing()),然後把
問題的處理集中一處。
可是 Exception 最大的缺點也是上面提到的特點:因為把某 logic
(e.g. doSomething() ) 與 它的問題處理分開了,所以容易遺漏,
想對整個流程(包括問題處理)理解的話,閱讀上就會困難。
有一篇文章寫得不錯,雖然我不完全認同。可是可以肯定的是,要寫
好的 Exception code 比大家想像中困難。用回傳值之類的方法雖然
看起來累贅,可是要寫一些能容易理解的 code 比較容易
http://www.joelonsoftware.com/items/2003/10/13.html
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 223.19.42.175
※ 編輯: adrianshum 來自: 223.19.42.175 (04/17 10:55)
→
04/17 10:56, , 1F
04/17 10:56, 1F
※ 編輯: adrianshum 來自: 223.19.42.175 (04/17 10:58)
討論串 (同標題文章)