For the last couple of weeks I’ve been paired with Lior on a large refactoring task that was long overdue. We did not have any specific bug to fix, but rather wanted to simplify some of the dustier corners of our codebase. This really helped me realize the importance of refactoring, and specifically of doing it frequently.
The first thing I noticed was that both of us struggled when reading the code; it was not badly written – there were messy parts and elegant parts like anywhere else – it was just alien to us. We did not know what the author meant when writing the code, the naming convention was confusing to us and the reasons behind some of the trickier stuff were a mystery to us.
Now, after major renaming, commenting out, deleting, simplifying and extracting, we believe the code is simpler and more readable. However, I believe that if we leave it at that in a couple of years another pair may be in the exact same situation – our code may be mystifying to them, no matter how self descriptive we tried to make it. By refactoring frequently this can be avoided, or at least minimized.
Refactoring is easy to neglect; in the TDD cycle we never forget to write tests, implement code and test it, but it’s easy to leave it at that once all tests passed. I intend to put emphasize on doing another refactor + test run on any code I product, in order to make sure I did my best to keep it simple. Also, when fixing something I fully intend to look beyond the immediate fix (which may be something small like adding an ‘if’ condition), and go over the entire method/class I modified. You may write code that flows like poetry, but after patching it a couple of times the rhymes will be off and the punch line is gone. This may not seem important when trying to get as many features as possible out the door, but missing it may have severe effect on the quality of the code base, the time it takes new people to learn it and how testable it is.