2017-09-26 48 views
1

例如:如何用相同的重複代碼塊來包圍不同的代碼塊?同時能夠返回不同的值

public Object foo(string something, Boolean flag, Object obj){ 
    try{ 
    if(flag){ 
     //some code 
    } 
} catch(Exception e) { 
    // handle exception 
} 
} 

public Object doo(string something, Boolean flag){ 
    try{ 
    if(flag){ 
     //different code 
    } 
} catch(Exception e) { 
    // handle exception 
} 
} 

public Object roo(string something, Boolean flag, Integer id){ 
    try{ 
    if(flag){ 
     //a bit of code 
    } 
} catch(Exception e) { 
    // handle exception 
} 
} 

我的問題是,有沒有辦法不具有在每個功能(例如在try-catch塊和IFS)的所有重複的代碼?這真的會清理我的項目,並會幫助我專注於重要的代碼。

我問過關於void函數的這個問題,並注意到所提出的解決方案(使用runnable)對返回類型不爲null的函數不起作用。有沒有不同的方式來實現這一點?

鏈接到我以前的(非常相關的)問題:How do I surround different blocks of code with the same repeating block of code?

回答

0

當你需要一個返回值,你可以用一個可贖回,而不是一個Runnable的。我修改了Joffrey在另一個線程中給出的示例:

class CallableExample { 
    public static void main(String[] args) { 
     CallableExample ce = new CallableExample(); 
     System.out.println(ce.foo("", true, "")); 
     System.out.println(ce.doo("", true)); 
     System.out.println(ce.roo("", true, 1)); 
    } 

    public Object foo(String something, Boolean flag, Object obj) { 
     return runCallable(something, flag, new Callable() { 
      @Override 
      public Object call() throws Exception { 
       return "foo"; 
      } 
     }); 
    } 

    public Object doo(String something, Boolean flag) { 
     return runCallable(something, flag, new Callable() { 
      @Override 
      public Object call() throws Exception { 
       return "doo"; 
      } 
     }); 
    } 

    public Object roo(String something, Boolean flag, Integer id) { 
     return runCallable(something, flag, new Callable() { 
      @Override 
      public Object call() throws Exception { 
       return "roo"; 
      } 
     }); 
    } 

    private Object runCallable(String something, Boolean flag, Callable c) { 
     Object result = null; 
     try { 
      if (flag) { 
       result = c.call(); 
      } 
     } catch(Exception e) { 
      // handle exception 
     } 
     return result; 
    } 
} 
0

查看模板方法設計模式和Execute Around成語。但是,如果你發現自己經常編寫能夠捕捉異常的代碼,那就是一種設計嗅覺:問問你自己爲什麼這樣做,以及是否真的有必要。通常讓異常傳播到調用上下文更好。

0

爲什麼在不同的方法使用相同的代碼,而不是寫同一套代碼單一功能具有的if-else-如果與嘗試捕捉邏輯,並儘量減少你的代碼 例如:

public Object foo(string something, Boolean flag, Object obj) { 
    try { 
     //convert the object type to primitive type data like int, String or any 
     if(flag) { 
      //your code 
     } 
    catch(Exception ex) { 
     //your code 
    } 
    //return the object; 
} 

轉換對象類型數據轉換爲原始類型並相應地使用它 如果使用其他邏輯

相關問題