blog dds

2012.01.11

Refactoring on the Cheap

The refactorings that a good integrated development environment can perform are impressive. Yet, there are many reasons to master some cheap-and-cheerful alternative approaches. First, there will always be refactorings that your IDE won’t support. Also, although your IDE might offer excellent refactoring support for some programming languages, it could fall short on others. Modern projects increasingly mix and match implementation languages, and switching to a specialized IDE for each language is burdensome and inefficient. Finally, IDE-provided refactorings resemble an intellectual straightjacket. If you only know how to use the ready-made refactorings, you’ll miss out on opportunities for other code improvements.

In this column, I describe how you can harness the sophistication of your editor and the power of command-line tools to perform many simple refactorings on your own. As a bonus, you’ll see that you can write and run most of them in less time than is required to fire up your favorite IDE.

Within Files

The basic tool for performing a refactoring within a file is the editor’s substitution command used in conjunction with regular expressions (see “Dear Editor,” IEEE Software, vol. 22, no. 2, 2005, pp. 14–15). In this section’s examples, I’m using the common Unix substitution syntax s/old/new/ and vi’s regular expression syntax; other editors offer similar functionality. Splitting a simple method call into two can be as easy as typing