Re: [問題] 程式的例外
例外就是例外阿
如果要把例外當成是邏輯的一部份
那就不是例外了
如果是這樣的話
我是採取以下的作法
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
→
04/17 12:06, , 1F
04/17 12:06, 1F
→
04/17 12:07, , 2F
04/17 12:07, 2F
→
04/17 12:07, , 3F
04/17 12:07, 3F
→
04/17 12:10, , 4F
04/17 12:10, 4F
→
04/17 12:10, , 5F
04/17 12:10, 5F
→
04/17 12:13, , 6F
04/17 12:13, 6F
→
04/17 12:13, , 7F
04/17 12:13, 7F
→
04/17 13:52, , 8F
04/17 13:52, 8F
→
04/17 13:58, , 9F
04/17 13:58, 9F
→
04/17 14:00, , 10F
04/17 14:00, 10F
討論串 (同標題文章)