A Catalog of Refactorings
About half of Martin Fowler's Refactoring book is devoted to a catalog of refactorings. Each of these is a relatively simple transformation; Fowler explains the mechanics of the change and provides examples (Figure 2.1). For another example, not in Fowler's book, see Figure 2.2.
FIGURE 2.1 Sample Refactoring
FIGURE 2.2 Sample Refactoring
This refactoring lets us replace the easy-to-read String version with a potentially more efficient StringBuffer version (or vice versa: many refactorings are appropriate to use "backward"). Some compilers can apply this particular rule for us automatically; then we can keep the readability and let the compiler do the work. For the example below, we'll apply this refactoring ourselves.
If all compilers did this reorganization automatically, would we still want this refactoring? I believe we would. The first form is shorter, but relies on the overloading of "+" in Java. The second version uses the (otherwise) uniform operator "." to handle method calls. If we ever wanted to replace the data type (using something other than String/StringBuffer), we'd be better off starting from the StringBuffer version.