Contact Us

Before you refactor...

Posted on 26/4/07 by Tim Koschützki

Have a solid Testbase

Whenever you do refactoring you should always ensure you have a solid test base. Not tests written on paper, but Unit Tests. The tests are essential, because even when you follow the refactorings' structures, you are a still a human-being and therefore make mistakes. You need solid tests. Simple.

It is vital to make your tests self-checking. Meaning that you alter how they print out their results. You could either make them print "OK" or "Something was wrong". Or you could of course tell them what went wrong. If you do not make your tests self-checking you lose much time manually checking numbers against numbers, strings against strings. Consider using a testing framework like Simpletest that prints nice messages like "Test #1 failed: got 'string1' when 'string2' was expected. It helps a lot and saves plenty of time.

It's essential to lean on tests. Writing tests takes up time...of course. But they will give you that *lost* time back when you alter the program later. They give you confidence about your code and prevent you from getting hairloss.

Compare with your requirements

You have to know what the code is supposed to do and what it is doing already before you refactor. Refactoring is good for getting from an overly complex solution to a simple one. You should not break anything or even lose functionality. Tripple-check with your requirements list, your specification and - if necessary - with your client, that nothing broke.

Make sure you have your refactoring hat on

As a programmer we usually wear two hats - the feature hat and the refactoring hat. It is absolutely critical that you do not add new functionality to your system when you are doing a refactoring. The risk of breaking things is just too high. Even with good tests - good meaning that they cover many state possibilities of your system - you can end up wasting too much time getting to know what is really going on. You will find yourself changing hats quite often. You start by trying to add a new function, and you realize this would be much easier if the code was structured differently. Swap hats and refactor for a while. Once it is better structured, swap hats again and get the new function working. You realize you could use some 3rd party code and you swap hats again. This could only take a couple of minutes. Always be aware of which hat you are wearing, though.

Besides that, keep the refactoring rhytmn in mind. Test, small refactoring, test, small refactoring.

Oh and did I say test? :)


You can skip to the end and add a comment.

This post is too old. We do not allow comments here anymore in order to fight spam. If you have real feedback or questions for the post, please contact us.