作者swpoker (swpoker)
看板java
標題Re: [問題] 程式的例外
時間Wed Apr 17 11:43:37 2013
例外就是例外阿
如果要把例外當成是邏輯的一部份
那就不是例外了
如果是這樣的話
我是採取以下的作法
interface Check{
boolean doCheck(State state);
}
check程式片段
void check(State state,Check [] checklist){
for(Check check:checklist){
if( check.doCheck(state) == false){
return ;
}
}
}
主程式應用:
Check[] checklist=new Check[]{
new Check(){
public boolean doCheck(State state){
if(state.money == 0){
state.doxxx();
state.error(xx);
return false;
}
return true;
}
}
, new Check(){
public boolean doCheck(State state){
if(state.money > 0 && state.money < state.price){
state.doxxx();
state.error(xx);
return false;
}
return true;
}
}
, new Check(){
public boolean doCheck(State state){
do_ok();
return true;
}
}
};
State state = new State();
docheck(state,checklist);
if(state.iserror()){
xxxx
}
我通常會比較欄惰
把檢查跟處理放再同一個類別
只是遇到這種狀況
我會把檢查跟邏輯放再同一個介面
然後自主程式抽離出來
再利用DJ方式注入
實現了OCP原則
如此
我可以無限擴充檢查與邏輯
而不用動到主程式
也可以針對單一檢查與邏輯測試
或是整個測試
例如
可以測試眾多檢查是否有重復的狀況->check101跟check303的條件是一樣的
提供給大家參考
※ 引述《adrianshum (Alien)》之銘言:
: 亂入一下。
: 看見很多討論 (甚至 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: 163.29.29.131
→ adrianshum:要是你把例外當成邏輯以外的去想,那很大可能你是捉錯 04/17 12:06
→ adrianshum:用神了。比如 Checked Exception 就是需要 caller 明確 04/17 12:07
→ adrianshum:去處理,這怎可能不當是邏輯一部份? 04/17 12:07
→ adrianshum:當然你要是說邏輯只包括 normal flow 不包 failure 04/17 12:10
→ adrianshum:handling logic 的話,你說的話就可以算對 04/17 12:10
→ adrianshum:本來exception就只是把問題回報在語言層面上加的抽象化 04/17 12:13
→ adrianshum:未有exception之前這些也是邏輯的一部份 04/17 12:13
→ swpoker:我對於例外的定義就是-不在正常流程中所發生的 04/17 13:52
→ swpoker:然後不要使用例外當作是邏輯~例 FileNotFoundException 04/17 13:58
→ swpoker:好吧~其實我是想說不要濫用例外而已~例外就只是例外阿 04/17 14:00