Java 重构代码以引发RuntimeException而不是返回值
由于代码重复,我需要重构现有代码 以下结构在疯狂类中出现10次以上:Java 重构代码以引发RuntimeException而不是返回值,java,refactoring,runtimeexception,Java,Refactoring,Runtimeexception,由于代码重复,我需要重构现有代码 以下结构在疯狂类中出现10次以上: public MyType doSomething(...) { MyType myType = ........ if (myType == null) { final String message = "..."; LOGGER.error(message); throw new XxxRuntimeException(message)); }
public MyType doSomething(...) {
MyType myType = ........
if (myType == null) {
final String message = "...";
LOGGER.error(message);
throw new XxxRuntimeException(message));
}
return myType;
}
我想重构LOGGER.error
并向如下新方法抛出新的RuntimeException
行:
private void logErrorAndThrowRuntimeException(String message) {
LOGGER.error(message);
throw new XxxRuntimeException(message));
}
问题是重构后,if
contion中没有返回值
我无法将异常类型从RuntimeException
更改为exception
,因为此应用程序具有疯狂的逻辑,需要抛出RuntimeExceptin
您知道如何将这两行代码重构为新方法并保持原始方法的逻辑不变吗?声明一个可丢弃的返回类型:
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;
}
声明可丢弃的返回类型:
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;
}