由于代碼重復,我需要重構現有代碼。以下結構在一個瘋狂的類中出現超過 10 次: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問題是重構后條件內沒有返回值。我無法將異常類型從 更改RuntimeException為Exception因為此應用程序具有瘋狂的邏輯并且需要拋出 RuntimeExceptin。知道如何將這兩行代碼重構為一個新方法并保持原始方法的邏輯不變嗎?
1 回答

縹緲止盈
TA貢獻2041條經驗 獲得超4個贊
聲明一個 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;
}
添加回答
舉報
0/150
提交
取消