有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在具有不同常量的代码上使用Extract方法?

鉴于我有如下代码:

void foo() {
  String str = "hello";

  a(str, 1);
  b(str, true);

  a(str, 2);
  b(str, false);
}

我想提取一个新方法c,比如:

void foo() {
  String str = "hello";

  c(str, 1, true);
  c(str, 2, false);
}

然而,自动提取方法重构将只提取a/b对中的一对。我猜它不喜欢不同的常数。我可以通过先提取一个局部变量,然后提取方法,然后内联以前提取的变量来解决这个问题,但我仍然需要手动查找所有实例。有了这么多的工作,当我看每一部分时,我也可以自己做完全的改变

我是否缺少一个技巧,让Eclipse知道如何更努力地搜索以提取这种类型的代码


共 (1) 个答案

  1. # 1 楼答案

    是的,您需要将常量提取到变量中,您可以将变量放在顶部,告诉工具将它们作为参数传递给提取的方法

    void foo() {
      String str = "hello";
      int constant = 1;
      boolean boolValue = true;
      a(str, constant);
      b(str, boolValue);
    
      constant = 2;
      boolValue = false;
      a(str, constant);
      b(str, boolValue);
    }
    

    采用提取方法时,应给出以下信息:

    public void c(String str, int constant, boolean boolVal){
        a(str, constant);
        b(str, boolVal);
    }