« Archives in November, 2010

Code Kata 1: The Closer You Get

karate.jpgI’ve already written about Code Katas and how they can help you become a better programmer; this time, I’m getting serious about it.

Like all craftsmen, we need to practice a lot; eight hours of professional software development is not enough, especially if a great share of these hours is dedicated to email and meetings. A carpenter is not just building houses but also tries out new ideas on his workbench in the basement; painters sketch and explore new combinations of paint and color. Photographers do it, musicians do it: everyone who wants to become better at their craft has to practice in a safe and dry place.

Today’s kata is a simple one. Imagine you have a set of numeric values. If I give you another value (which may or may not be within the set), find a value from the set that matches the given value as close as possible. Don’t write any code yet! Proceed as indicated below.

  1. Think about the problem and draw a picture that illustrates the problem.
  2. What special cases do you see?
  3. Try to come up with a simple algorithm (use pseudo code, flowcharts, whatever you prefer).
  4. Write down a few good test cases and mentally check your algorithm against them. Select a programming language of your choice and code a dummy implementation that always returns the same (wrong) result.
  5. Code your test cases and execute them against your dummy implementation. You don’t have to use unit testing frameworks like JUnit; use the simplest way of comparing results to expected results and flag an error if there is no match.
  6. Watch your tests fail.
  7. Implement your algorithm.
  8. Execute your tests and debug your code until all tests pass.
  9. If you haven’t done it yet: single-step through every line of your code.

Bonus exercise:

  1. Turn your algorithm into a generic routine that is suitable for a library; that is, support different value types (floating point types, integer types).