I enjoyed reading Refactoring, by Martin Fowler et al. The book seems to treat refactoring both as a technique and as a philosophy.
As a technique, refactoring is simply “change made to the internal structure of software to make it easier to understand and cheaper to modify without changing the observable behavior of the software.” Most of the book is a reference of refactorings: motivation, mechanics, and examples for things like “Extract Method” and “Replace Conditional with Polymorphism”. I love to write good code, so I actually liked reading the reference material – each refactoring represents a code change that has the potential to make it better.
As a philosophy, the book tries to help the reader know when refactoring should take place, and which refactorings should be used. One practical motivation for refactoring is to improve the design and understandability of code before you add a feature or fix a bug. To determine which refactorings are needed, you’ll notice “bad smells” in the code – one chapter is devoted to some of the more common smells, including duplicated code, long methods, switch statements, etc. One quickly begins to see the author’s idea of what good code looks like; the reader must decide if he agrees.
The trouble with refactoring is the “without changing the observable behavior” part. It’s hard to guarantee that your changes haven’t changed anything. In fact, from page 8: “Before you start refactoring, check that you have a solid suite of tests. These tests must be self-checking.” The process of writing these tests is not described in detail – and rightly so – but the need for a test suite is important to keep in mind. Writing good tests is certainly harder than the process of refactoring itself.
I’m not yet sold on the philosophy behind refactoring, but I want to give it a try. Good refactoring tools are becoming more common – the prospect of avoiding the busy work of refactoring is very attractive, and would be a strong influence to try it out, though there’s still that pesky test suite to create...
Writing this review, I realize that I should read the opening chapters again. In case it isn’t clear, I highly recommend this book.