I have spent the last three weeks working on a prototype for some really cool CLR plumbing. One of the fun things about writing prototypes is that you get to ignore all of that engineering stuff and focus on trying to figure out if something is possible. Well, after three weeks of very focused work, I discovered that everything that I want to do is in fact possible. Now comes the hard part: trying to create a build that actually does something useful.
One of the things that you quickly discover about any prototype codebase is that it is extremely brittle and resistant to change. Why? Because you were too busy figuring out if stuff is possible vs. engineering solid software. Now, the temptation always is to throw out that prototype and start again. But I’m resisting that temptation because I need to continue to prototype after I’ve built an intermediate build that I intend on using for a period of time.
To enable further work on the prototype codebase, I need to refactor the existing code. One of the reasons that the prototype is so complex is that there is duplicate code scattered all over the code base. There are complex data structures intermingled with core behavior. I’m abusing COM horribly (like calling interface methods from threads that haven’t called CoInitialize() yet — and no, it’s not because I’m lazy, it’s a much more complicated problem than that). I’ve got bizarre global variables sitting in my code because I haven’t designed the caching objects to take care of them yet. I need to fix my code base before I can use it, much less extend it.
I tend to refactor fairly naturally since I’ve been programming for a long time. Earlier this year, however, I discovered Martin Fowler’s most excellent book: Refactoring: Improving the Design of Existing Code. I’ve spent the better part of yesterday and today refactoring my code base. However, instead of doing stuff like “hmmm, I need to move this redundant code into a separate method”, I’ve been forcing myself to look up the refactoring method in the list of refactorings in Fowler’s book. So, I’ve been saying stuff like “Extract Method” to myself instead. The benefit of this is that I’m learning lots of interesting refactoring methodologies that I wouldn’t have otherwise used, and it creates a vocabulary that I can use to communicate with other developers. Try it, I’m sure you’ll grow to love it like I have.
Another tip for those times when you are heavily refactoring your codebase: use your version control system. Make small changes, test those changes, and check those changes back into your VCS. Believe me, it’s an awesome safety net for those times when you’ve got your code dissected into a million pieces and you can’t remember how to put it back together again …