Yesterday evening I read the latest blog post from Uncle Bob about how refactoring can help you find dead code in your code base. A great post, you can find it here. Apparently, Uncle Bob has a policy that says that whenever he has code up in an editor, he has to try to leave it in a better shape than he found it. I think this is a great policy and although I think I will have problems applying this principle myself I will at least try to apply a policy of leaving code I work on in a better shape than when I started….
I decided to do just that this evening when I was going to do a small change in some code I wrote a couple of years ago. I was never really that pleased with the portion of code I now was going to change, it was written close to a project deadline. As a concequence, the code was quite hard to understand which again means that it hasn’t been re-factored since. Ideally, I would like to do some heavy refactoring and make the code a bit more object oriented, but this time around the project is in a code freeze so it didn’t feel right to do the heavy re-factoring now. But if I was going to practice my new principle some change was needed. Applying TDD, I wanted to write the test first, quicly realizing that the test code was in quite a mess. A lot of duplication and code that was difficult to read, After applying the builder pattern on some of the value objects and a couple of extract methods, the test code looked a whole lot better and actually possible to read.
I was now ready to write the actual test for the new functionality to add, with my new builder objects this should be easy to accomplish.Red bar, ready to change the code to reflect the new requirement. First thing to do: Change the method name to reflect what it actually does. Not enough though as it turns out that the method is strangely factored. It’s getting late, need to continue this tomorrow. However, the code is (I think at least) in a better shape than it was before I started.