由于代码重复,我需要重构现有代码。
以下结构在一个疯狂的类中出现超过 10 次:
public MyType doSomething(...) {
MyType myType = ........
if (myType == null) {
final String message = "...";
LOGGER.error(message);
throw new XxxRuntimeException(message));
}
return myType;
}
我想将 LOGGER.error
重构为新方法,如下所示:
private void logErrorAndThrowRuntimeException(String message) {
LOGGER.error(message);
throw new XxxRuntimeException(message));
}
这样做的问题是重构后 if
条件内没有返回值。
我无法将异常类型从 RuntimeException
更改为 Exception
,因为此应用程序具有疯狂的逻辑,需要抛出 RuntimeExceptin。
知道如何将这两行代码重构为新方法并保持原始方法的逻辑不变吗?
最佳答案
声明 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;
}
关于java - 重构代码以抛出 RuntimeException 而不是返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56386733/