This is a translation of the dutch post I did for my company’s blog.
Recently a friend of mine handed me a copy of Martin Fowlers Refactoring: Improving the Design of Existing Code (that’s what friends are for). The book is considered a standard on refactoring en can still be seen as a must-read for every programmer, although it published in 1999.
Refactoring means to rewrite code, in small, safe (backed by unittests) steps. Doing this cautiously ensures that there is no loss of functionality and results in a decrease of error-proneness of the code and an increase in readability and maintainability. As Folwer mentions: the compiler reads your code once, while your and your colleagues will be gazing over it and changing it a lot times during coding. Making sure your code is readable (really readable, like a book) will save you and your coworkers a lot of time!
Fowlers book also helps you maintain the DRY (Don’t Repeat Yourself) principle. If you have to duplicate a piece of business logic in your code, it WILL cause you trouble. When the logic has to be altered, you can be sure that one of these places will be forgotten.
Before Fowler starts working on a piece of code, to fix a bug or add new functionality, he’ll often start with a refactoring to better understand the code. This may sound strange, but it is almost impossible to write perfect code from the start. I don’t mean working code, but code that is open enough to support all the possible questions, extensions or other changes and still is small enough to only do what it needs to do. If you accept the fact that you are going to have to refactor, and that it’s not a failure for you as a programmer, you can write better, cleaner code.
My favorite tool to do this (in .Net) is the fantastic ReSharper. A lot of the refactorings in the book can be done automatically and safely with this tool. It has an enormous list of functionalities, and I’m still discovering new uses every day.
An important note on refactoring is knowing when to stop. Knowing when to start is one thing, but at least as importing is knowing when you’ve refactored enough, or when a refactoring isn’t going as planned and the best thing to do is undo your changes. Huge reworks are done one refactoring at a time. You can always come back tomorrow to do the rest of them. As long as you leave the code in a better state than it was before, your good!
Refactoring fits perfectly in the iterative Agile process and is a corner-stone of Extreme Programming (XP). It’s no coincidence that Martin Fowlers can be found underneath the Agile Manifesto. Clean code will also provide value for the customer. Although it sounds counter intuitive, investing time in refactoring saves time writing code. A win-win!
If you haven’t, read the book and start refactoring.
You’ll love it, it’s a way of life.