Refactoring To Make Improvements Possible
By Adrian Sutton
I’ve had an interesting experience the last couple of days – I’ve been trying to add some major new functionality into our list code. The code is exceptionally well tested and fairly easy to understand but it wasn’t clear how to write a test that described the functionality I wanted to add.
I started off by writing an acceptance test for what I wanted and then started drilling down to what I needed, but it was leading me off into a rewrite of our list code because it was too difficult to see how to reuse the existing code for what I wanted. In the end, I decided to almost reverse refactor the existing code to extract out the logic that I needed. I say reverse refactor because instead of making the code simpler to read and understand, it was making it more complex – it really felt quite wrong to be applying the refactorings.
By the time I left this afternoon though, I’d reached the point where the logic I wanted to reuse was quite clearly separated and the design was starting to be cleaned up again. I’ve got some duplicate code lying around because I haven’t finished cleaning up yet, but I’m quite happy with the way it’s all shaping up. What has surprised me the most is how much more code I can reuse than I had expected to. Taking the refactorings one step at a time and depending on the tests to make sure I had things right has led to a much better design and a clearer path forward than I had ever thought possible.
One question that remains is what new tests I should be writing. While all the code has simply been refactored and is still covered by the old tests, the refactoring has exposed a bunch of new opportunities for atomic tests. For example, a couple of new classes have been split out – it’s possible to add atomic tests for those to verify that they do the subset of the task that they claim to, no more and no less – currently we only have tests for the task as a whole. So far I don’t have any fear that it’s wrong so I’m not worrying about writing tests, but I’m trying to stay alert to my fear level to be sure that tests are added as soon as they provide benefit.