Given this simplified scenario:
private String name;
private String getString() {
return "Hello, " + name + "!";
}
I would like to capitalize the name with a private static capitalize(String)
method. If I extract name
into a method (CTRL-2 + M), then I get a private String capitalize()
method that references the name
field.
Here's the desired result: (before implementing capitalization)
private static String capitalize(String name) {
return name;
}
I really want capitalize
to be static, because I can then move it to some other class (SHIFT-ALT-V). Also, when there are multiple fields, moving them to parameters is tedious.
Is there any way to extract a method, or introduce an indirection that passes fields as parameters? It does not need to be a single refactoring; a combination might still save typing and human error.
Here's a sequence that would work:
name
to a new local variable (Alt-Shift-L
), call it "toCap"toCap
, call it "capitalize"static
tocapitalize
toCap
(Alt-Shift-I
).Now you can move
capitalize
to the place of your liking.For this exact scenario, it may not be worth it (simpler to directly create the static capitalize method), but I can see that in more complex situations this sequence of refactorings could actually help.
The general pattern behind this sequence is: before extracting a method, prepare all the arguments you want to pass into the method using fresh local variables. When the method has been extracted, inline the unwanted local variables.