Refactoring

Refactoring means transforming code without changing its functionality. Consider renaming, which is the simplest form of refactoring. If you rename a local variable from rose to daisy, it would smell as sweet.

Much has been written on refactoring, such as Refactoring: Improving the Design of Existing Code (Addison Wesley). Before Eclipse and similar tools were available, programmers had to do refactoring manually or with simple text substitutions. For example, in the vi editor, running the command :1,$s/rose/daisy/g will replace "rose" with "daisy" everywhere in the current file.

If you've ever tried this, you know it's usually a bad idea. Your simple search-and-replace operation can change more than just the variable you intended, even with a clever substitution string. Plus, if you need to change multiple files, you'll have to go to a scripting language such as Perl.

Here's how it works in Eclipse. To rename a symbol (i.e., a class, method, variable, etc.), select it in the editor and press Alt+Shift+R (Refactor → Rename). Type in the new name and press Enter to perform the change. Done!

If you like, you can select the Preview button before performing the changes; this will show you what the modified source will look like (see Figure 25). You can also undo the refactoring (Ctrl+Z or Edit → Undo) if you change your mind.

Here's another handy refactoring supported by Eclipse: to move a class from one package to another, simply go to the Package Explorer view and drag ...

Get Eclipse IDE Pocket Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.