跨类层次结构重构try-catch

时间:2019-03-28 00:41:10

标签: java exception refactoring dry code-duplication

假设您有以下代码:

class Base {
    void method() throws Exception {
        try {
            //Lots of code here
        } catch (Exception e) {
            //handle it (very little code here)
        }
    }

class Derived extends Base {
    @Override
    void method() throws Exception {
        try {
            //Lots of code here (same code as in base class)
        } catch (Exception e) {
            //handle it (very little code here; also same as base class)
        } catch (Error e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

因此,如我们所见,除了派生类具有额外的catch子句外,方法是相同的。有什么好方法可以在这里减少重复的代码?

0 个答案:

没有答案