August 22, 2009

Solo refactoring

In my most recent post I described a recent refactoring exercise. Refactoring can be a dangerous exercise, if not done properly. Any time you alter code, there is a risk that a bug or performance issue can be introduced. Hence the strong attraction to the “if it ain’t broke, don’t fix it” rule of thumb.

But if done correctly, refactoring mercilessly is a very strong practice. According to Martin Fowler:
Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior. Its heart is a series of small behavior preserving transformations. Each transformation (called a 'refactoring') does little, but a sequence of transformations can produce a significant restructuring. Since each refactoring is small, it's less likely to go wrong. The system is also kept fully working after each small refactoring, reducing the chances that a system can get seriously broken during the restructuring.
My intent in refactoring the code was to make it more readable and understandable, without changing its external behavior. No adding features, no removing features, no bug fixes. And certainly no new bugs.
I think I was pretty successful with the code cleanup part, but I was not careful enough. Just a handful of hours after I posted, a reader named Ivan submitted a comment pointing out a case I had neglected to handle.

A case which was handled in the code I changed during my refactoring. I had broken the cardinal rule: I had introduced a bug.

August 19, 2009

Intention Revealing Code

I just watched the video of Robert Martin’s Norwegian Developers Conference presentation titled “Clean Code III - Functions”. In his hour-long talk, he talks about methods you can use and principles you should follow to make your code more understandable and more readable. He also show some sample code that is difficult to understand at first reading, and then some refactorings of that code that increase its understandability.

I won’t go into the details of his talk; you should watch it yourself. It’s well worth the hour-long investment. But his refactoring example reminded me of a refactoring exercise that I recently did.