Saturday 6 September 2008

Test Driven Development and a Code Kata

(Please click on the images to get a more readable version).


This week I thought of trying out a CodeKata problem and choose Kata 4 . The kata requires you to read a data file, parse it , extract some values and print the difference between them. A simple exercise one would say.

To explain the problem in brief. A data file containing the results of the football league is provided. The requirement is to extract the name of the team with the lowest goal difference in For and Against goal values. I decided to make this problem a bit more exciting by not just coding along a 'happy path' but also looking out for scenarios where there might be no valid data rows or there might be two teams matching the lowest goal difference criteria.

Using a test driven approach, I hacked out a set of basic JUnit tests to parse a valid data row and extract the For and Against goal values. My data row looked somewhat like this.



and the tests to extract the values from this data row looked like this:

Now that I was getting the For and Against Goal values, all I needed was to calculate their difference and store the team name (& goal difference) in a 'results list'. The tests for doing this were accomplished as below:

As evident from the test, my 'controller' class has ONE main function which is updateLowestGoalDifferenceTeam(). This function performs the core business processing in terms of updating the list holding the lowest goal difference team names. This function is given as below.




The function gets the list holding the team name, extracts the goal difference values and compares the same against the goal difference value passed to it as a parameter in a HashMap. If the passed in value is lower, the existing team becomes a part of the list.



In all the Kata was a simple excercise but it was instructive in analysing the data structures that could be used and in studying the different approaches that could be taken to solve this problem. If you would like to compare your efforts with mine or wanted to know more about the solution, ping me for the complete code as an Eclipse project.

No comments: