Wednesday, January 04, 2006 3:46 PM | rahel luethy | 4 comment(s)

inline refactoring trick

consider the following scenario: you have a class Foo which offers a non-static method getFoo():

public class Foo {
 
 public String getFoo() {
  return "foo";
 }

}

you're wearing the refactoring hat and have decided to change the method to be static. of course you could just add a static modifier and fix all compile errors, but let's assume that your method is used a gazillion times in your project, so this is not really an option...

tada! here comes the inline refactoring trick (I haven't invented it, but somehow I can't find the original article anymore):

  1. perform a rename method refactoring and change getFoo() to getBar():
    public class Foo {
     
     public String getBar() {
      return "foo";
     }
    
    }
    
  2. duplicate the method, rename one of the duplicates back to getFoo(), and add the static modifier to the one still called getBar():
    public class Foo {
     
     public String getFoo() {
      return "foo";
     }
    
     public static String getBar() {
      return "foo";
     }
    
    }
    
  3. replace the complete contents of getFoo() with a static call to getBar():
    public class Foo {
     
     public String getFoo() {
      return Foo.getBar();
     }
     
     public static String getBar() {
      return "foo";
     }
    
    }
    
  4. here comes the magic: perform an inline refactoring on the getFoo() method, which will change all former callers of getFoo() to now invoke Foo.getBar()
  5. rename getBar() back to getFoo()
  6. take off that STUPID HAT
note that the same magic works for more complicated scenarios, like refactoring a class with static methods into a singleton.

10:50 PM | Blogger Etienne Studer said...

Or use IDEA's 'Make static' refactoring.... ;-)

10:58 AM | Blogger rahel luethy said...

what about 'Convert class with static methods to evil Singleton' refactoring. does IDEA offer that as well? ;-)

3:15 AM | Blogger Etienne Studer said...

Sure, IDEA does. Just do a Structural Search and Replace (which is much smarter than basic textual search and replace).

Template:
Foo.$method$($params$)

params occurrence count: 0 to Unlimited

Replacement:
Foo.getInstance().$method$($params$)

...and you're done.

I would not want to code without SSR.

10:02 AM | Blogger rahel luethy said...

you win ;-)