Code kata 3: Refactoring
This kata was inspired by a truly ugly piece of code we came across in Redgate Towers. It had a whole bouquet of code smells: long methods, a lot of indentation, static variables, inconsistent naming, code that was duplicated with small modifications, and a couple of small bugs. And, gloriously, it was just a few hundred lines long and carried out one clear, isolated function. We saw it and realised in an instant that we were looking at the ideal material for a refactoring kata.
Rather than just ask the participants to refactor the code, we put the emphasis on writing unit tests, with the idea that this would drive the need to refactor.
Your job is to write unit tests for the code, refactoring the code to create testable units.
- Keep your check-ins small by limiting each one to a single refactoring.
- Should you find any bugs, fix them as you go by creating a failing test and then making it pass; then return to refactoring.
How did it go?
We find it curious that, even though we had quite a few pairs who attempted the problem, all of them appeared to struggle with the thorny issue of what’s the first thing you’re going to change, when there aren’t any tests?
A number of groups tried to write tests for the module’s current behaviour, and then refactored ensuring the tests remained green. Their problem, though, was that they ended up with tests for behaviour that was obviously broken, and you had to wonder how useful these were.
Another group started out using ReSharper refactorings, assuming – and we would agree with them – that they were safe to do without tests. Their idea had been to switch to writing unit tests as soon they could, but the way things turned out, lunchtime appeared and they never wrote any tests at all, showing perhaps how hard it is to stop once you’ve set out in a particular direction.
On reflection, we feel that a better approach might be to refactor to remove the static variables first, as we think these presented the greatest obstacle to separating the code into testable units. It would be interesting to see if the results are more promising if we were to set the same kata again, giving this as the first step.
Was this article helpful?