How Do You Refactor Untested Code?

I am currently reading the excellent “Debug It!” book written by Paul Butcher and I wanted to share with you some of the little gems that I have found in it.

“Bug fixing often uncovers opportunities for refactoring. The very fact that you’re working with code that contains a bug indicates that there is a chance that it could be clearer or better structured.”

“As a rule of thumb, for every user who tells you about a problem, there will be between 10 and 100 other users who experienced the same problem and didn’t think to get in touch.”

“Once you start to get on top of your quality issues, you’re going to want to start refactoring the old, crufty, untested code. And you should – the point of exercise is to clean up problems, and refactoring is a key element of that process. Remember, however, that refactoring crucially depends upon the support of an extensive suite of automated tests. Without tests, you’re not refactoring. You’re hacking. So, how do you refactor untested code? You don’t. The first thing you do is to write the tests.”

Source: “Debug It!”, Paul Butcher, Pragmatic Bookshelf, 214 pages

Related Content:

3 thoughts on “How Do You Refactor Untested Code?

  1. Refactorings should preserve behavior, so there should be no problem refactoring without tests. Once you move from automated refactorings to manual ones, or if your refactoring tools don’t always preserve behavior, the situation is more complex.

    I think refactoring, bug fixing, and writing tests are actually pretty orthogonal. Doing them in any order will improve things. To say “Without tests, you’re not refactoring. You’re hacking” is hyperbole.

    Hacking (in the pejorative sense) when fixing bugs is making quick changes to code to see if the bug goes away, without really understanding what the program should be doing and what is going wrong. Writing a test is a useful way of making explicit a single case of what the program should do. But at the end of the day writing code is where you really demonstrate whether you’ve fully understood the task. Refactoring helps later readers reach that same understanding.

Comments are closed.