java-refactoring-remove-parameter

java-refactoring-remove-parameter

熱門

在 Java 語言中使用移除參數進行重構

3.7萬星標
4569分支
更新於 2026/7/14
SKILL.md
readonlyread-only
name
java-refactoring-remove-parameter
description

在 Java 語言中使用移除參數進行重構

使用移除參數重構 Java 方法

角色

您是重構 Java 方法的專家。

以下是 2 個範例(標題為重構前後的程式碼),代表移除參數

重構前程式碼 1:

public Backend selectBackendForGroupCommit(long tableId, ConnectContext context, boolean isCloud)
        throws LoadException, DdlException {
    if (!Env.getCurrentEnv().isMaster()) {
        try {
            long backendId = new MasterOpExecutor(context)
                    .getGroupCommitLoadBeId(tableId, context.getCloudCluster(), isCloud);
            return Env.getCurrentSystemInfo().getBackend(backendId);
        } catch (Exception e) {
            throw new LoadException(e.getMessage());
        }
    } else {
        return Env.getCurrentSystemInfo()
                .getBackend(selectBackendForGroupCommitInternal(tableId, context.getCloudCluster(), isCloud));
    }
}

重構後程式碼 1:

public Backend selectBackendForGroupCommit(long tableId, ConnectContext context)
        throws LoadException, DdlException {
    if (!Env.getCurrentEnv().isMaster()) {
        try {
            long backendId = new MasterOpExecutor(context)
                    .getGroupCommitLoadBeId(tableId, context.getCloudCluster());
            return Env.getCurrentSystemInfo().getBackend(backendId);
        } catch (Exception e) {
            throw new LoadException(e.getMessage());
        }
    } else {
        return Env.getCurrentSystemInfo()
                .getBackend(selectBackendForGroupCommitInternal(tableId, context.getCloudCluster()));
    }
}

重構前程式碼 2:

NodeImpl( long id, long firstRel, long firstProp )
{
     this( id, false );
}

重構後程式碼 2:

NodeImpl( long id)
{
     this( id, false );
}

任務

應用移除參數來改善可讀性、可測試性、可維護性、可重用性、模組化、內聚力、低耦合及一致性。

始終返回完整且可編譯的方法(Java 17)。

在內部執行中間步驟:

  • 首先,分析每個方法,找出未使用或多餘的參數(即可從類別欄位、常數或其他方法呼叫取得的值)。
  • 對於每個符合條件的方法,從其定義及所有內部呼叫中移除不必要的參數。
  • 確保方法在移除參數後仍能正常運作。
  • 僅在單一 java 區塊內輸出重構後的程式碼。
  • 不要移除原始方法的任何功能。
  • 在每個修改過的方法上方加入一行註解,說明移除了哪個參數及其原因。

待重構的程式碼:

現在,評估所有包含未使用參數的方法,並使用移除參數進行重構。