How do I extract code into a static method in Eclipse, passing fields as parameters?

523 views Asked by At

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.

2

There are 2 answers

3
Stephan Herrmann On

Here's a sequence that would work:

  1. Extract the field reference name to a new local variable (Alt-Shift-L), call it "toCap"
  2. Extract a method from the reference to toCap, call it "capitalize"
  3. Add modifier static to capitalize
  4. Inline the extra local variable 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.

0
Nicolas On
  1. Extract the part of the method that you want to become static. Yes, this will still refer to fields.
  2. Make the new method static.
  3. In the caller, pass the fields as parameters (use the warnings about fields not being accessible from the static method as a reference).
  4. CTRL-1 the extracted method in the caller, and pick + Change method: Add parameter

The extracted static method should now have parameters that hide the fields because they have the same name.