Book Review – Working Effectively with Legacy Code
23 Feb 2018I am feeling a bit embarrassed that I read Working Effectively with Legacy Code by Michael Feathers only recently. It has been recommended so many times to me and it's the top mentioned book on Stackoverflow but somehow I also expected that it doesn't contain any new revelations for me – which is far from reality.
You will have heard Michaels definition of legacy code before: Legacy code is code without tests. It's no surprise that the book focuses a lot on strategies for getting legacy code under test. It consists of many rather small chapters that each focus on a certain aspect of working with legacy code with chapter titles like This Class is Too Big and I Don't Want It to Get Any Bigger or I'm Changing the Same Code All Over the Place. I've been reading the book cover to cover but those chapters can also be read standalone, especially when coming back to the book later. The examples are mostly in Java and some in C++ (that poses some unique problems).
The most valuable aspect of the book is that it provides a very structured way of thinking about legacy code. Not only by providing recipes but also by defining certain terms, the most important one being the seam, a place in your code that you can use to replace some behaviour in tests. This can be to separate some unwanted blocks of code (e.g. a remote http call, a database interaction) or to sense an interaction – to be able to see that a certain code path is being taken and maybe even look at the variables at this point. To get seams into place you use dependency breaking techniques. The book contains a catalog of those in the last part, some examples being Extract and Override Call or Extract Interface .
Only while listening to a recent interview with Michael on SE-Radio I noticed that the book doesn't mention a technique you will hear often when people talk about legacy code: Implementing a system wide test before doing any changes, e.g. by using something like Selenium or golden master testing. Instead Michael focuses on writing tests that are close to the change and will do some refactorings without having tests in place to get the system in a testable state.
I'd be very interested how a book like this (that I still consider very relevant in its 2004 state) would look like if it was written today with all the more advanced mocking and system test tools available. I'm excited that there is an announcement for a new book on the same topic by Michael.
A lot of people tend to shy away from working with legacy code. But even in your greenfield project it won't take long to see areas that need improvement. So the techniques in this book are definitively relevant for everybody. If you haven't read the book yet – go ahead and do it.