IntelliJ Refactor to use LoD
Asked Answered
P

1

3

Say I have some class Foo

class Foo {
    protected String x = "x";

    public String getX() {
        return x;
    }
}

I have a program that uses Foo and violates LoD

class Bar {
    protected Foo foo;

    public Bar() {
        this.foo = new Foo();
    }

    public Foo getFoo() {
        return foo;
    }
}

public static void main(String [] args) {
    Bar bar = new Bar();
    String x = bar.getFoo().getX(); 
}

Refactoring to use LoD looks like this:

class Bar {
    protected Foo foo;

    public Bar() {
        this.foo = new Foo()
    }

    public String getFooX {
        return foo.getX();
    }
}

public static void main(String [] args) {
    Bar bar = new Bar();
    String x = bar.getFooX();
}

IntelliJ-IDEA has a lot of refactoring methods (e.g. extract to method, extract to variable, inline).

Is there a method in IntelliJ-IDEA that will refactor code like bar.getFoo().getX() to look like bar.getFooX()?

Pentad answered 2/7, 2015 at 18:20 Comment(0)
S
6

Assuming that your example is Java code, you could do the following:

  1. Extract method on bar.getFoo().getX() (creating getFooX())
  2. Move the created method getFooX() to Bar if necessary
  3. Invoke Find and Replace Code Duplicates on getFooX()
  4. Invoke Convert To Instance Method on getFooX()
  5. Optionally Structural Replace $a$.getFoo().getX() with $a$.getFooX() if you forgot step 3;-)
  6. Inline all invocations of getFoo() (should be only in getFooX())
Spinster answered 3/7, 2015 at 9:37 Comment(3)
I was able to do it in only two steps. 1. Extract method (find and replace shows up automatically) 2. Move method (convert to instance method shows up there)Pentad
Here is a follow-up questionPentad
Yes, you're right of course, the Convert To Instance Method does the move implicitly. Good find. Edit: wait a minute, you do the Move and Convert To Instance Method show up? Not for me. And the duplicate finder that shows up automatically only searches in the same file for me...Spinster

© 2022 - 2024 — McMap. All rights reserved.