Monday, August 25, 2008

Refactor Extract Method

Refactor Extract Method, I had never used this much until last week. Neal Ford was talking it up in the productive programmer and a co-worker mentioned off hand that he used it all the time.
So I gave it a try and have must say, I've never used anything better when working with poorly written legacy code. crtl-shift-M bye bye 40 lines of nested if statements and for-loops hello descriptive name. Besides making the code prettier and easier to read I found it does 2 important things.
  1. After blocks of code are broken up into specific groupings (methods), it's really easy to start re-organizing the code. With a lot of this code I'm working, the initial writer took short cuts, and bundled things together that made the logic confusing. Once I started extracting methods, it became really easy to start reordering and regrouping how these methods were called into something that read much easier.
  2. After I was able to reorder things suddenly the code became declarative. The method that was doing all the work, said what it was going to do, and if you wanted to read the details, just pop into the methods. That this simple refactoring could lead to nice declarative code, for me is the real selling point.
So I had never thought refactor extract method was particularly useful, but now anytime I see code I don't want to look at, I just refactor it away, eclipse handles the magic, I end up with declarative code, and I love it!

1 comment:

ekerwin said...

Are you nuts? I can't believe you've never used Extract Method before. It is literally one of the only tools in the refactor toolbelt that I consider worth it. That and rename variable are literally all you should be doing during a good refactor session. What the hell else are you doing when you refactor? Are you, gasp, REWRITING?!?! Shame.

 
Web Statistics