Monday, September 27, 2004

Refactoring Tips

by Asim Jalis

I just had an extremely positive refactoring experience. We refactored out a piece of code so that we were able to reuse it for several different cases. Once we extracted the essense of the repetition, we got several cases for free. When refactoring creates leverage like this it is extremely satisfying. This made me wonder, what leads to more of this kind of high-leverage refactoring? Why did it happen this time, and why does it not happen every time we program. Here are the things that I think contribute to it. 1. The other person in the pair has be interested in doing this. If the other person is not interested in creating this elegance he will not be open to exploring the different shapes the code can take. 2. The tests must be refactored, just like the code. In our case we refactored the tests first. The refactoring in the code fell out of the refactoring in the test. 3. The concept of premature optimization can act as a force that opposes seeing similarity in different things. Optimization should be postponed. 4. Having the tests in place and then doing it in tiny steps really helped. Now I am eager to have this experience again.