简体   繁体   English

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

[英]How can I use Extract Method on code that has different constants?

Given I have code like the following: 鉴于我有如下代码:

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

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

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

I would like to extract a new method c like: 我想提取一个新的方法c像:

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

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

However, the automated Extract Method refactoring will only extract one of the a / b pairs. 但是,自动提取方法重构将仅提取a / b对之一。 My guess is that it dislikes the differing constants. 我的猜测是它不喜欢不同的常数。 I can work around this by extracting a local variable first, then extracting the method, then inlining the previously extracted variable, but I still have to find all the instances by hand. 我可以通过以下方法解决此问题:首先提取局部变量,然后提取方法,然后内联先前提取的变量,但是我仍然必须手动查找所有实例。 With that amount of work, I might as well just make the full change myself when I am looking at each part. 通过这么多的工作,我不妨在查看每个零件时自己进行全部更改。

Is there a trick I am missing to let Eclipse know to search a little harder to extract this type of code? 有什么技巧让我知道让Eclipse更加努力地搜索以提取这种类型的代码吗?

Yes, you need to extract your constants into variable that you can put in the top to tell your tool to pass them as arguments to the extracted method. 是的,您需要将常量提取到变量中,然后将其放在顶部以告诉工具将其作为参数传递给提取的方法。

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

Doing an extract method should give the following: 进行提取方法应提供以下内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM