Franz Ebner
Franz Ebner

Reputation: 5096

IntelliJ: Refactor signature to use parameters properties

Is it possible in IntelliJ to do this kind of refactoring

public class Demo {

    public long sum(Model model) {
        int a = model.getA();
        int b = model.getB();
        System.out.println(model.getA());
        System.out.println(model.getB());
        return (long) a + b;
    }

    //refactor to

    public long sum(int a, int b) {
        System.out.println(a);
        System.out.println(b);
        return (long) a + b;
    }

    private static class Model {
        private int a;
        private int b;
        private int c;

        //getter & boilerplate
    }
}

would be quite nice IMHO to reduce complexity in certain cases.

Googled around for a while and tried various refactoring dialogues- couldn't find anything better than "Change Signature" yet.

EDIT: refined Example to have multiple usages per parameter

Upvotes: 1

Views: 64

Answers (1)

LppEdd
LppEdd

Reputation: 21124

Great question!
Yes, this is possible using the combination of Extract parameter and Inline variable.

  1. Starting point

    enter image description here

  2. Over getA(), right click > Refactor > Extract > Parameter (or ctrl + alt + p on Windows).
    The result is

    enter image description here

    Do the same with getB().

  3. Invoke the Inline variable quick-fix/refactoring on the local variables (ctrl + alt + n on Windows)

    enter image description here

  4. Admire the result and rename accordingly

    enter image description here


I can do all of that in a matter of 5 seconds using shortcuts and quick-fixes navigation ;)

Upvotes: 1

Related Questions