October 2, 2017
Manual Refactoring : Rename
As a trainer, I work mostly in Java and C# to reach the widest audience possible. In Eclipse, IntelliJ and with Resharper (or the new Rider IDE), I have a decent suite of automated refactorings to work with.
I find that when I'm working without my beloved automated refactorings, I get sloppy. You need to be extra disciplined when refactoring by hand.
So I thought I'd write some blog posts to illustrate with examples some core foundational manual refactorings. Started with the easiest one: Rename.
Most editors have features that can find references to classes, methods, variables, fields and constants etc.
Here's some code that, in its current form, doesn't make much sense.
I want to rename these elements to make it self-explanatory. First of all, just what the heck is a "Place Repository" in this context? It's a Flight.
If I type a new name for the class - because of the rules of Java - I then have to rename the file, too. Even if your language doesn't have that rule, I'd recommend doing it anyway so the file names don't become misleading.
The code's still broken. I need to go to the references and update them next.
OK. Now I should be able to run the tests to make sure I haven't broken the code. DO NOT FORGET TO RUN THE TESTS!
And that's a complete Rename refactoring. Of course, the local variable should be renamed, too. But that would be a second Rename refactoring. Even when we're doing them manually - especially when we're doing them manually - we need to maintain the refactoring discipline and see those tests pass as often as possible.
Now, editing individual references is a bit of a drag. Most editors also offer a simple way of doing multiple renames quickly, with Find/Replace.
Let's rename the variable using this feature.
Find/Replace can remove a lot of the donkey work out of renaming symbols. But take care. It's powerful, and if we get sloppy can rename stuff we didn't intend. As with all refactorings, perhaps a good to make sure you have an easy way back if it goes wrong. Before I renamed that variable, I committed to my local Git sandbox.
And then re-run the tests before moving on to renaming some of the other decidedly cryptic names in this code.
So, that's manual Rename. Easy.
Posted 2 years, 3 months ago on October 2, 2017