这个问题是后续for this
说我有一些Foo课。

class Foo {
    protected String x = "x";

    public String getX() {
        return x;
    }
}
我有一个使用Foo并违反LoD(Law of Demeter)的程序。
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();
}
我可以分两步重构此代码以使用LoD。
  • -m bar.getFoo().getX()-> getFooX(bar)(提取到方法,还查找并替换出现的位置)
  • F6 getFooX(bar)-> bar.getFooX()(移至实例方法,还查找并替换出现的事件)

  • 使用Bar的程序不再违反LoD。
    class Bar {
        protected Foo foo;
    
        public Bar() {
            this.foo = new Foo();
        }
    
        public Foo getFoo() {
            return foo;
        }
    
        public String getFooX() {
            return foo.getX();
        }
    }
    
    public static void main(String [] args) {
        Bar bar = new Bar();
        String x = bar.getFooX();
    }
    
    我想知道是否有一种方法可以使IntelliJ中的自定义重构方法将这两个步骤合并为一个。
    编辑
    我收到了JetBrains的回复,其中包含指向预先存在的功能请求的链接。如果您觉得有用,请对其投票!

    编辑
    至少有一种方法可以检查Demeter法则问题。
    java - IntelliJ中的简单自定义重构-LMLPHP

    Here is a gist包含将仅查找违反LoD的检查配置文件。您可以import it into IntelliJ

    最佳答案

    getFooX()方法添加到Bar之后,我将使用编辑> 查找> 用以下表达式在结构上替换:

    搜索模板:

    $instance$.getFoo().getX()
    

    替换模板:
    $instance$.getFooX()
    

    它完美地完成了工作。也许您可以向$instance$变量添加一些约束以缩小搜索范围,但这仅在您使用该方法名称包含多个类时才有用。

    10-07 12:28
    查看更多