IntelliJ重构使用LoD

mic*_*den 2 java refactoring intellij-idea law-of-demeter automated-refactoring

说我有一些课Foo

class Foo {
    protected String x = "x";

    public String getX() {
        return x;
    }
}
Run Code Online (Sandbox Code Playgroud)

我有一个使用Foo并违反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(); 
}
Run Code Online (Sandbox Code Playgroud)

重构使用LoD看起来像这样:

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();
}
Run Code Online (Sandbox Code Playgroud)

IntelliJ-IDEA有很多重构方法(例如,提取到方法,提取到变量,内联).

IntelliJ-IDEA中是否有一个方法可以重构代码bar.getFoo().getX()看起来像bar.getFooX()

Bas*_*ers 5

假设您的示例是Java代码,您可以执行以下操作:

  1. 提取方法bar.getFoo().getX()(创建getFooX())
  2. 如有必要,将创建的方法移动getFooX()Bar
  3. 调用查找和替换代码重复getFooX()
  4. 调用转换为实例方法getFooX()
  5. 可选结构替换$a$.getFoo().getX()$a$.getFooX(),如果你忘了第3步;-)
  6. 内联所有调用getFoo()(应该只在getFooX())