I have to deal with some old legacy code, that unfortunately had the coding style of declaring all the variables at the beginning of a method.
The code looks something like this as an example:
public String doSomething(boolean showStars) {
StringBuilder builder = null;
String result = "";
String prefix = null;
int i;
try {
prefix = "result: ";
if (showStars) {
builder = new StringBuilder();
builder.append(prefix);
for (i = 0; i < 10 ; i++) {
builder.append('*');
}
result += builder.toString();
} else {
builder = new StringBuilder();
builder.append(prefix);
for (i = 0; i < 20; i++) {
builder.append('.');
}
result += builder.toString();
}
} catch (SomeException ignored) {
}
return result;
}
Now I want to apply the following refactoring on my codebase (http://refactoring.com/catalog/reduceScopeOfVariable.html), so that my code will look like something like this, so I can refactor further with Extract Method.
public String doSomething(boolean showStars) {
String result = "";
try {
String prefix = "result: ";
if (showStars) {
StringBuilder builder = new StringBuilder();
builder.append(prefix);
for (int i = 0; i < 10 ; i++) {
builder.append('*');
}
result += builder.toString();
} else {
StringBuilder builder = new StringBuilder();
builder.append(prefix);
for (int i = 0; i < 20; i++) {
builder.append('.');
}
result += builder.toString();
}
} catch (SomeException ignored) {
}
return result;
}
To my surprise I did not find any useful tool for helping me with this kind of refactoring, neither freely available nor any commercial product.
Does anybody know of any tool that supports this kind of refactoring? I looked into NetBeans/Eclipse/IntelliJ IDEA and none of that seem to support this kind of Refactoring out of the box. Because I have about 3000 legacy methods that unfortunately are structured like that, and some are up to 1500 LoC per method, so doing this by hand would be very very tedious.
Ctrl + 1
and choose "Inline local variable" to reduce its scope. After that, highlighted code can be used to extract a method withAlt + Shift + M
.