Although I've owned a copy for well over a year I've never felt like reading Working Effectively With Legacy Code but having just finished reading an excellent chapter I'm realizing this was a mistake.
As you probably know the book is really about getting code under test, legacy code being code without tests. Thus if you are working with a codebase with little or no test coverage, and where dependencies make it hard to test, it's going to be a very useful book.
Since we already have good test coverage and generally don't have any major problems getting our code under test I didn't think it was that relevant. However I just read an excellent chapter (6) that explains how to make changes to code that doesn't have tests whilst ensuring that your new code has tests. The chapter documents a few patterns:
- Sprout Method - You cannot get the method that you are adding the behavior to under test. Put the new behavior into a new method with its own tests, call the new method from the method you want to add the behavior to.
- Sprout Class - Perhaps you can't get the existing class under test or the new responsibility does not fit the existing class, create a new class for the new behavior. Hopefully by doing this you improve the design and have extracted a meaningful concept.
- Wrap Method - Take the existing method and extract the code from it into a new method, leaving the original method calling the new one. Now add a call to the new method that adds the behavior you want to add. This maintains the interface used by the callers.
- Wrap Class - Extract a decorator or a wrapper class that delegates to your existing class but adds behavior before/after the call(s). The book recommends using decorator sparingly but its useful when there are many class to the class being wrapped.
The book then goes on to compare the choices.
Like I really liked the section. It focusses on changes that allow you to get your code under test but they could be part of a process that eventually improves the design and brings your entire code base under test.
I also like the fact that he has given these changes simple memorable names, and for that reason alone I'm now glad I've started reading the book.