【问题标题】:refactor code to throw RuntimeException instead of return a value重构代码以抛出 RuntimeException 而不是返回值
【发布时间】:2019-05-30 23:08:05
【问题描述】:

由于代码重复,我需要重构现有代码。

以下结构在一个疯狂的类中出现超过 10 次:

public MyType doSomething(...) {
    MyType myType = ........
    if (myType == null) {
        final String message = "...";
        LOGGER.error(message);
        throw new XxxRuntimeException(message));
    }
    return myType;
}

我想将LOGGER.errorthrow new RuntimeException 行重构为这样的新方法:

private void logErrorAndThrowRuntimeException(String message) {
    LOGGER.error(message);
    throw new XxxRuntimeException(message));
}

这样做的问题是重构后if contition 内没有返回值。

我无法将异常类型从 RuntimeException 更改为 Exception,因为此应用程序具有疯狂的逻辑并且需要抛出 RuntimeExceptin。

知道如何将这两行代码重构为一个新方法并保持原方法的逻辑不变?

【问题讨论】:

    标签: java refactoring runtimeexception


    【解决方案1】:

    声明一个 Throwable 返回类型:

    private XxxRuntimeException logErrorAndThrowRuntimeException(String message) {
        LOGGER.error(message);
        // You can throw here, or return if you'd prefer.
        throw new XxxRuntimeException(message));
    }
    

    那么你可以在调用处抛出这个,表示if体不能正常完成:

    public MyType doSomething(...) {
        MyType myType = ........
        if (myType == null) {
            final String message = "...";
            throw logErrorAndThrowRuntimeException(message);
        }
        return myType;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-03
      • 1970-01-01
      • 1970-01-01
      • 2019-01-12
      • 2014-09-03
      相关资源
      最近更新 更多