情况:我正在处理遗留代码并试图提高可读性。以下示例应可视化意图:
private static final String CONSTANT_1 = "anyValue";
private static final String CONSTANT_2 = "anyValue";
private static final String CONSTANT_3 = "anyValue";
private static final String CONSTANT_4 = "anyValue";
private static final String CONSTANT_5 = "anyValue";
private final SomeType someField = new SomeType();
private void contentOfSomeMethods(){
someMethod(someField, CONSTANT_1, true);
someMethod(someField, CONSTANT_2, true);
someMethod(someField, CONSTANT_3, true);
someMethod(someField, CONSTANT_4, false);
someMethod(someField, CONSTANT_5, false);
}
private void someMethod(SomeType type, String value, boolean someFlag) { }
想象一下,使用大约 50 个常量对 someMethod 进行了大约 50 次调用。我想对该代码进行安全自动重构,以便contentOfSomeMethods
方法更改为
private void contentOfSomeMethods(){
doItWith(CONSTANT_1);
doItWith(CONSTANT_2);
doItWith(CONSTANT_3);
doItNotWith(CONSTANT_4);
doItNotWith(CONSTANT_5);
}
并且生成了两个额外的方法:
private void doItWith(String value) {
someMethod(someField, value, true);
}
private void doItNotWith(String value) {
someMethod(someField, value, false);
}
天真的方法是提取局部变量中 contentOfSomeMethods
中的所有常量,然后使用提取方法重构来创建所需的方法。然后内联局部变量。但此解决方案无法扩展。
另一种方法是使用正则表达式搜索和替换,但这不是安全的重构,因此我可能会在不知不觉中破坏代码。
您有什么更好的建议吗?您知道 Eclipse 的一些插件可以做到这一点吗?
最佳答案
我不知道有任何实用程序可以直接执行此操作。
我认为使用正则表达式是唯一可行的方法。首先,您需要创建两个目标方法 doItWith
和 doItNotWith
。然后,您可以突出显示方法 contentOfSomeMethods
的内容,按 Ctrl+F,并使用以下正则表达式:
Find:
someMethod\(someField, (\w*), true\);
Replace with:doItWith(\1);
然后
Find:
someMethod\(someField, (\w*), false\);
Replace with:doItNotWith(\1);
一定要检查“正则表达式”和“选定行”。这是它的图片:
正则表达式与 (\w*)
的函数调用中使用的常量相匹配,然后在 \1
的替换过程中使用它。仅在选定的行上使用此正则表达式可最大限度地减少破坏不相关代码的可能性。
关于java - 如何在eclipse中提取将字段或常量值转换为参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33119494/