If you’ve read Michael Feathers’ book, Working Effectively with Legacy Code, you’ll know that he presents his techniques for refactoring clearly and simply. My favorite is his metaphor of finding the “seams” in the code to break it apart then “sew” it back together again. If you’ve attempted to implement some of these techniques in your own project you’ll also know that it’s not easy. It is slow arduous work, and when there are no unit tests it can be scary.

Crisp hosted Michael Feathers’ course:”TDD and Refactoring Techniques” this week in Stockholm. I hoped that some secret knowledge of how to refactor easily would be revealed, something that was just too elusive to express in a book. Instead my experience that refactoring is difficult was reaffirmed.

The exercises were relatively simple, as all such exercises are, yet even they took several steps to refactor to a workable state. When we had existing unit tests the refactoring process moved along at a faster, smoother pace. We didn’t need to discuss as much and we weren’t afraid of making the changes. When we didn’t have the Unit Tests, we made mistakes, even with relatively straightforward refactorings like extracting a method or a class. It’s really easy to transpose variables as it turns out!

One of the valuable lessons you learn during the course is that the proper editing techniques can really help minimize the mistakes you can make. It is easy to transpose variables, or parameters, or to name them differently if you just retype them in another file. Instead, it’s better to copy and paste your method names, you eliminate spelling mistakes and retain naming conventions. Focusing the refactoring on code cleanup, without introducing messier code, or even worse: new defects.

Finally, the most important technique you’re exposed to is pragmatic programing. Just because some authority has decreed that there is a “right way” to do things, it may not at all be applicable to your current situation. Examine your code, look at your problem and decide for yourself if the “right way” is the right solution for you. You may have to change your program for the worse, but know that it’s just a temporary step to get you a little bit closer to your clean code. Maybe you’ll have to break a singleton pattern to introduce a test, make a method public, add a testing field in your class. It’s ok! You’re moving towards cleaner code, sometimes you get a bit messy on the way 🙂

Get in touch via my homepage if you have questions or comments!

One response on “Refactoring

Comments are closed.