重构代码以抛出 RuntimeException 而不是 return 值
refactor code to throw RuntimeException instead of return a value
由于代码重复,我需要重构现有代码。
下面的结构疯狂出现了10次以上class:
public MyType doSomething(...) {
MyType myType = ........
if (myType == null) {
final String message = "...";
LOGGER.error(message);
throw new XxxRuntimeException(message));
}
return myType;
}
我想将 LOGGER.error
和 throw new RuntimeException
行重构为这样的新方法:
private void logErrorAndThrowRuntimeException(String message) {
LOGGER.error(message);
throw new XxxRuntimeException(message));
}
问题在于重构后 if
条件中没有 return 值。
我无法将异常类型从 RuntimeException
更改为 Exception
,因为此应用程序的逻辑很疯狂,需要抛出 RuntimeExceptin。
知道如何将这两行代码重构为新方法并保持原始方法的逻辑不变吗?
声明一个 Throwable return 类型:
private XxxRuntimeException logErrorAndThrowRuntimeException(String message) {
LOGGER.error(message);
// You can throw here, or return if you'd prefer.
throw new XxxRuntimeException(message));
}
那你可以在调用处抛出这个来说明if body不能正常完成:
public MyType doSomething(...) {
MyType myType = ........
if (myType == null) {
final String message = "...";
throw logErrorAndThrowRuntimeException(message);
}
return myType;
}
由于代码重复,我需要重构现有代码。
下面的结构疯狂出现了10次以上class:
public MyType doSomething(...) {
MyType myType = ........
if (myType == null) {
final String message = "...";
LOGGER.error(message);
throw new XxxRuntimeException(message));
}
return myType;
}
我想将 LOGGER.error
和 throw new RuntimeException
行重构为这样的新方法:
private void logErrorAndThrowRuntimeException(String message) {
LOGGER.error(message);
throw new XxxRuntimeException(message));
}
问题在于重构后 if
条件中没有 return 值。
我无法将异常类型从 RuntimeException
更改为 Exception
,因为此应用程序的逻辑很疯狂,需要抛出 RuntimeExceptin。
知道如何将这两行代码重构为新方法并保持原始方法的逻辑不变吗?
声明一个 Throwable return 类型:
private XxxRuntimeException logErrorAndThrowRuntimeException(String message) {
LOGGER.error(message);
// You can throw here, or return if you'd prefer.
throw new XxxRuntimeException(message));
}
那你可以在调用处抛出这个来说明if body不能正常完成:
public MyType doSomething(...) {
MyType myType = ........
if (myType == null) {
final String message = "...";
throw logErrorAndThrowRuntimeException(message);
}
return myType;
}