Maarten
Maarten

Reputation: 918

How to refactor in Intellij - method with parameters to class with fields

Given a method

public class SomeClass{ 
    public void methodName (Param1 param1, Param2 param2, Param3 param){
        ...
    }
}

called as

SomeClass someObject = new SomeClass();
someObject.methodName(x, y, z);

What's the fastest way to refactor someObject.methodName(x, y, z); in IntelliJ to

public class MethodNameHandler{
    private Param1 param1;
    private Param2 param2;
    private Param3 param3;

    public MethodNameHandler(Param1 param1, Param2 param2, Param3 param3){
        this.param1 = param1;
        this.param2 = param2;
        this.param3 = param3;
    }

    public void methodName(){
            ...
    }
}

called as

new MethodNamehandler(x, y, z).methodName();

Upvotes: 3

Views: 537

Answers (1)

Jaroslaw Pawlak
Jaroslaw Pawlak

Reputation: 5578

In IntelliJ 14.1.4 and 15.0:

Step 1:

Place a caret on the method declaration, press ctrl + alt + shift + t (or cmd instead of ctrl if on Mac) and select 7. Parameter Object.... Type in a name (I used Holder) for a new class and press Refactor.

The popup will ask you for default value for Holder, leave Leave blank so the compiler will tell you if anything went wrong. In this case, no default value is needed so it should be refactored correctly without any compiler errors.

Step 2:

Again place a caret on the edited method, ctrl/cmd + alt + shift + t, select 4. Move.... The Holder class should be available and selected. Press Refactor.

Step 3:

Finally, in your Holder class inline getters generated in the first step. Place a caret on getter declaration and press ctrl/cmd + alt + n. Unfortunately, it has to be done separately for each of them.

Upvotes: 3

Related Questions