Monday, September 24, 2007


I'm doing some refactoring on my spare time. Sounds horrible? Well it is. But I have some old obligations that I'm trying to finish off so I can devote all my time and energy to my new job.

My main advise for refactoring is: take one small step at the time.

For me there are mainly two cases.

1) I know the code needs refactoring but don't know how/ where to start. What I do then is that I try to locate one line of bad code or duplication and try to refactor that. And with every change I run unittests to make sure that the piece of code still works.

2) I know the code needs refactoring and I see room for improvements in every single line of the code. What I do here is still to move in small steps. Change one thing at the time and run unittests. Bad code and little unittesting always seems to be tied together, so chances are you'll end up writing a complete testsuite for the module you're refactoring. But take that extra time! Unittests are essential for refactoring, without it you'll almost never know what the effects of your changes are.

I know that when you have many ideas of code improvements it can be a pain to stop and write tests. I mean, I have an idea and then I wanna try it right away, right? This really is a problem: you have to catch all these ideas or you might forget them, but you can't act on all of them at one time. I most often solve this by writing a comment saying: FIXME and then what I want to do. This has proven to be quite useful; often when you do major refactoring you'll end up not needing some of the old code. The unneeded code is often the one that you had a nice refactoring for. I think the reason for this is that, when you're refactoring you'll see a problem that needs to be solved. You then try out every solution you can find, but sooner or later you'll eventually stick with one and this makes parts of the others obsolete.

That was about what I had to say about refactoring. ( Besides the usual advises: always strive for DRYness, encapulation, orthogonality, etc ). I'll definitely get back to this subject when I finally get to read Martin Fowlers book Refactoring.

No comments: