SOKAHH: Coding Dojo – Legacy Code Kata
Yesterday I participated in the monthly SOKAHH meeting – this time we met for a Coding Dojo. The Kata we performed was a so called Legacy Code Kata authored originally by Sandro Mancuso as part of a conference talk: Testing and Refactoring Legacy Code.
What the Kata is about
The central class we were interested in this Kata is the class TripService. Of course untested following the definition of Legacy Code by Michael Feathers (Working Effectively with Legacy Code).
In the workspace we found an empty test stub waiting to be filled. Most obviously the central point of the Kata was to write the test.
Spoiler Warning! Some Results
I think it’s most interesting to perform this Kata without knowing much more. For us it ended in a discussion on the different approaches we followed. So I recommend not to read on if you want to perform this Kata.
It was interesting to see different approaches to deal with TripService. Some started to read the TripService’s code to understand it and to write a test matching their understanding of the code. Others tried the code, i. e. without reading the code but only the interface trying how it would work for example with null values.
The latter one was the approach taken by our pair. We didn’t want to do much mocking or guessing what the code is about. So we just started a first test without actually knowing what will happen by calling the (one and only) method of TripService with the argument null. The result was an exception (no, not NullPointerException). We took this result as the intended behavior. So our first test stated that it expects the exception to be thrown. Actually this is the most central rule I learned about Legacy Code:
Whatever the behavior of the legacy code is – it is the intended one.
The last missing tests were added using Code Coverage to detect which parts of the code have not yet been covered by a test.
All of us learned about the code while testing. Derived from the statements in the discussion no one grasped the idea of the code at first glance when we started. But at the end some of us even dared to refactor the code in that way that it reflects what we had learned the code is about.
Thoughts which came into my mind while doing the Kata were very familiar to me: “What the heck is this code about?” “We get an empty list as result of this test setup? I didn’t expect that.” Thus I recommend this Kata to everyone who has to deal with Legacy Code and I bet you will have some interesting insights.