在IntelliJ下使用instance method替換static method

大家都知道在絕大多數情況下,我們都不應該是用static方法。但如果真的有了,比如說是在遺留系統中有這樣的代碼,我們應該怎麼樣“安全”的重構呢?

給一個簡單的例子,假設我們有一個類叫做MyMath,代碼如下:

MyMathTest.java

public class MyMathTest {
    @Test
    public void shouldReturnSumOfTwoNumbersWhenAdd() {
        assertThat(MyMath.add(1, 1), is(2));
    }
}

MyMath.java

public class MyMath {
    public static int add(int a, int b) {
        return a + b;
    }
}


方法一:手動替換

1.拷貝static方法的body到另一個臨時方法裏

MyMath.java
public class MyMath {
    public static int add(int a, int b) {
        return a + b;
    }

    public int add2(int a, int b) {
        return a + b;
    }
}

2.delegate方法調用

public static int add(int a, int b) {
        return new MyMath().add2(a, b);
}

3. inline static方法

public class MyMath {

    public int add2(int a, int b) {
        return a + b;
    }
}

public class MyMathTest {
    @Test
    public void shouldReturnSumOfTwoNumbersWhenAdd() {
        assertThat(new MyMath().add2(1, 1), is(2));
    }
}

這樣就達到了替換的目的。

4. 重命名add2到add,完


方法二:intellij的convert to instance method

1.改變方法簽名(Command/Ctrl + F6),傳入一個MyMath的instance

public class MyMath {
    public static int add(int a, int b, MyMath myMath) {
        return a + b;
    }
}

public class MyMathTest {
    @Test
    public void shouldReturnSumOfTwoNumbersWhenAdd() {
        assertThat(MyMath.add(1, 1, new MyMath()), is(2));
    }
}

2.使用intellij的convert to instance method

選中add,然後在refactor中選中convert to instance method。


在彈出的窗口中選擇instance parameter爲myMath。


然後就大工告成:

public class MyMath {
    public int add(int a, int b) {
        return a + b;
    }
}

public class MyMathTest {
    @Test
    public void shouldReturnSumOfTwoNumbersWhenAdd() {
        assertThat(new MyMath().add(1, 1), is(2));
    }
}


總結:

在開始學重構的時候,最好是從手動重構開始,包括最簡單的提取方法這些,都最好從手動開始,到後面,你重複了足夠次數以後,儘量採用IntelliJ的自動重構來進行重構

發佈了154 篇原創文章 · 獲贊 17 · 訪問量 87萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章