Video: No-red refactoring

The more I code, the more I’ve learned to appreciate keeping the code clean even during complex refactorings. By “clean”, I mean that the code always compiles and the test always run.

I often find myself in a situation where I have a method call that’s starting to accumulate parameters. Something like this:

showPersonCreateForm<span style="color: #009900;">(</span>writer, firstName, firstNameErrorMessage, lastName, lastNameErrorMessage,....<span style="color: #009900;">)</span><span style="color: #339933;">;</span>

After three or four parameters, the need to refactor is starting to become evident. I would rather have something like this:

CreatePersonForm form <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> CreatePersonForm<span style="color: #009900;">(</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>
form.<span style="color: #006633;">setFirstName</span><span style="color: #009900;">(</span>firstName<span style="color: #009900;">)</span><span style="color: #339933;">;</span>
form.<span style="color: #006633;">setFirstNameErrorMessage</span><span style="color: #009900;">(</span>firstName<span style="color: #009900;">)</span><span style="color: #339933;">;</span>
form.<span style="color: #006633;">setLastName</span><span style="color: #009900;">(</span>firstName<span style="color: #009900;">)</span><span style="color: #339933;">;</span>
form.<span style="color: #006633;">setLastNameErrorMessage</span><span style="color: #009900;">(</span>firstName<span style="color: #009900;">)</span><span style="color: #339933;">;</span>
form.<span style="color: #006633;">show</span><span style="color: #009900;">(</span>writer<span style="color: #009900;">)</span><span style="color: #339933;">;</span>

This is one of the more complex simple refactorings you can make, and it requires several steps. In this five minute video, I show how to perform such a refactoring without any steps that break my code:

The screencast was created using the free BB FlashBack Express on Windows. All the magic you see happening while I program is either ctrl-space (complete) or ctrl-1 (quick fix).

Can you modify your code without going thought long stages of nothing working? I think you can!

This story, "Video: No-red refactoring" was originally published by JavaWorld.

Related:

Copyright © 2010 IDG Communications, Inc.