IntelliJ中的简单自定义重构 [英] Simple Custom Refactoring in IntelliJ

查看:161
本文介绍了IntelliJ中的简单自定义重构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题是后续为此

说我有一些课Foo。

class Foo {
    protected String x = "x";

    public String getX() {
        return x;
    }
}

我有一个使用Foo并违反LoD的程序( 德米特法则)。

I have a program that uses Foo and violates 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。

I can refactor this code to use LoD in two steps.


  1. m bar。 getFoo()。getX() - > getFooX(bar)(提取到方法,也可以查找和替换出现次数)

  2. F6 getFooX(bar) - > bar.getFooX() (转到实例方法,也找到并替换出现)

  1. m bar.getFoo().getX() -> getFooX(bar) (extract to method, also find and replace occurrences)
  2. F6 getFooX(bar) -> bar.getFooX() (move to instance method, also find and replace occurences)

使用 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中制作自定义重构方法这将把这两个步骤合并为一个。

I am wondering if there is a way to make a custom refactoring method in IntelliJ that would consolidate these two steps into one.

编辑
我收到了JetBrains的回复,其链接指向已有的功能要求。如果你发现这个有用,请投票!

EDIT I got a reply from JetBrains with a link to a pre-existing feature request. Please vote on it if you find this useful!


Hello Michael,

Hello Michael,

似乎我们在YouTrack中有类似的请求:
https://youtrack.jetbrains.com/问题/ IDEA-122400 。请随意投票
并发表评论。

Seems we have similar request in YouTrack: https://youtrack.jetbrains.com/issue/IDEA-122400. Feel free to vote for it and leave comments.

祝你好运,Yaroslav Bedrov JetBrains

Best regards, Yaroslav Bedrov JetBrains

编辑
至少有一种方法可以检查Demeter法的问题。
截图http://i59.tinypic.com/2s80ft0.png

这是一个要点,其中包含检查配置文件只会查找LoD违规。您可以将其导入IntelliJ

Here is a gist that contains an inspection profile that will just look for LoD violations. You can import it into IntelliJ.

推荐答案

getFooX()方法添加到 Bar ,我会使用以下表达式修改> 查找> 以结构方式替换

After adding the getFooX() method to Bar, I would use Edit > Find > Replace Structurally with the following expressions:

搜索模板:

$instance$.getFoo().getX()

替换模板:

$instance$.getFooX()

完美地完成工作。也许您可以在 $ instance $ 变量中添加一些约束来缩小搜索范围,但只有在您拥有多个具有该方法名称的classess时才会有用。

It does the job perfectly. Maybe you can add some constraints to $instance$ variable to narrow the search but that would only be useful if you had multiple classess with that method name.

这篇关于IntelliJ中的简单自定义重构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆