Approximity blog home
1 of 1 article InfoSyndicate: full/short

Zen Refactoring   24 May 05
[print link all ]
Alex Chaffee posted this to the xp-list.
 Yesterday I was pairing with Patrick, our new intern. He's great,
 smart as a whip, and willing to learn. (When I told him we write tests
 first, he laughed, incredulously, but then I said No, really, I'm
 actually serious, and he listened, and later, he said, Oh, now I see.)
 At the end of a long successful refactoring (turning a clutch of
 static methods into instance methods), we were sort of buzzing and
 didn't want to stop, were casting about for other refactorings to do
 in the same class. I suggested a technique I only just then gave a
 name to, that I've done occasionally on my own for a long time, but
 hadn't yet taught: Zen Refactoring.

 "Just let your eyes unfocus and scroll through the code and look for
 refactorings. Look for duplication; look for too-long or
 too-deeply-indented code blocks. When you notice something odd, don't
 read it, just select it, hit Extract Method (ctl-alt-M), and hit
 random keys for the name. Then focus your eyes again and see what
 you've done."

 I demonstrated. The first time we hit a bunch of print statements with
 repeated formatting -- it worked, but the refactoring was tedious,
 with marginal payoff. But the second time was golden. I saw a blurry
 if-else block; the first arm meandered for 15 or 20 deeply-indented
 lines, the second for fewer; their logic appeared opaque and disjoint.
 But after extracting the first block as a method, lo and behold:

 if (something() || other()) {
  customerId = sdlfjds(x, y, z);
  } else {
    user = someOtherExistingMethod();
    customerId = user.getUserId();
 }

 IDEA had figured out that the result of that meander was a single
 value, and returned it from the new method. It was instantly clear
 that we should rename the extracted method
 customerIdForSomethingOrOther", and extract the whole conditional as
 "getCustomerId". Shift-F6, ctl-alt-M, high five.

 Then it was Patrick's turn. Not quite as much of a slam-dunk but still
 a worthy refactoring. I can't wait to get an incredulous laugh from
 the next one I spring this on...

 

Powered by Rublog