How can I apply the “move method” refactoring with IntelliJ IDEA?

前端 未结 5 737
感情败类
感情败类 2021-02-01 17:53

I want to be able to move an instance method from one class to another class (\"Move method\" from Fowler\'s \"Refactoring\") in IntelliJ IDEA. Unfortunately, when I try \"Move.

相关标签:
5条回答
  • 2021-02-01 18:04

    if theMethod() has nothing reference to the host class(TheClass), you can make this method static and then use "Move" command. After the method was moved to the target class, you should remove the static keyword.

    0 讨论(0)
  • 2021-02-01 18:05

    The Move Method refactoring in IDEA only considers moving the method into classes related to it, i.e. used as its parameter or return value, or called from inside the method. Which is kinda logical: if the method has nothing concrete to do with the target class, why should it be there? OTOH I found this limiting in some cases where I still had a valid reason to move the method. So I had to do it by hand.

    0 讨论(0)
  • 2021-02-01 18:11

    In intellij 13.1 (dont' know in previous version) it could be done with the

    Choose Refactor | Extract | Delegate on the main menu

    but there is a "strange" limit, apparently: it could be done only with a new freshly created class. So you have to do apply this refactoring without creating the "OtherClass" (it will be create directly when you apply the refactoring).

    So a real "move" of method on an alredy created class seems missing, quite strange behaviou

    0 讨论(0)
  • 2021-02-01 18:12

    There is another method. Imagine you have the code:

    public int field;
    
    public void foo(int a) {
        assert field == a;
    }
    

    And you want to make foo static. Select the whole body of the method and preess Alt+Ctrl+M (Extract method). Type the same name of the method. Check "Declare static" checkbox (available only if the method only reads and doesn't modify the fields) and press Ok. So you get:

    public void foo(int a) {
        foo(a, field);
    }
    
    private static void foo(int a, int field) {
        assert field == a;
    }
    

    Move static method wherever you want and use old foo's body to call it.

    0 讨论(0)
  • 2021-02-01 18:17

    In IntelliJ 14-15 do the following:

    1. Position the caret on theMethod().
    2. press Ctrl/Cmd+F6 (Change signature).
    3. Introduce new parameter: Type=TheOtherClass, Name=theOtherClass, Default value=new TheOtherClass()
    4. Refactor
    5. Then press F6 (move) and move the method to theOtherClass.

    You will end up with:

    public class TheClass {
        public void doStuff() {
            int i = new TheOtherClass().theMethod();
        }
    }
    public class TheOtherClass {
        int theMethod() {
            System.out.println("Hello World!");
            return 0;
        }
    }
    
    0 讨论(0)
提交回复
热议问题