Comments

05/21/05: Zen Refactoring

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...



Comments made

You can find the lightest, most comfortable and stylish oakley sunglasses at these stores. May of these websites also carry a catalog of a wide range of <a href="http://www.cheapoakleyglass...">cheap oakley sunglasses</a> that can be easily downloaded. They also have a comprehensive information page, articles and reviews for more information on various technologies, thus making the selection process a bit easier. They also offer <a href="http://www.cheapoakleyglass...">discount oakley sunglasses</a> that are UV400 protected and are backed by a 30-day guarantee.
04/26/12 02:28:23

Add comment

Sorry, but due to blog comment spam, I have to ask you to create an account before you post a comment. Please log in (using the form on the top right of the page) or click here to create an account: Create an account!