0

說我有一些類Foo的IntelliJ重構使用毀滅之王

class Foo { 
    protected String x = "x"; 

    public String getX() { 
     return x; 
    } 
} 

我有一個使用Foo和違反毀滅之王

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(); 
} 

重構使用毀滅之王程序是這樣的:

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有很多重構方法(例如提取到方法,提取到變量,內聯)。

IntelliJ-IDEA中是否有方法將這樣的代碼重構爲bar.getFooX()

回答

4

假設你的例子就是Java代碼,你可以做到以下幾點:

  1. 提取方法上bar.getFoo().getX()(創建getFooX()
  2. 如有必要
  3. 調用移動創建方法getFooX()Bar查找並替換代碼重複getFooX()
  4. 調用轉換爲Instanc E法getFooX()
  5. 可選結構替換$a$.getFoo().getX()$a$.getFooX()如果你忘了第3步;-)
  6. 內嵌的getFoo()所有調用(應該僅在getFooX()
+0

我能做到這一點只在兩個步驟。 1.提取方法(查找和替換自動顯示) 2.移動方法(轉換爲實例方法顯示在那裏) – michaelsnowden

+0

這裏是[後續問題](http://stackoverflow.com/questions/31213864/ custom-refactoring-methods-intellij) – michaelsnowden

+0

是的,你當然是對的,*轉換爲實例方法*隱式執行。很好的發現。編輯:等一下,你做*移動*和*轉換爲實例方法*顯示?不適合我。而自動顯示的重複查找器只會在同一個文件中爲我搜索... –