I’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.
- Think about the problem and draw a picture that illustrates the problem.
- What special cases do you see?
- Try to come up with a simple algorithm (use pseudo code, flowcharts, whatever you prefer).
- 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.
- 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.
- Watch your tests fail.
- Implement your algorithm.
- Execute your tests and debug your code until all tests pass.
- If you haven’t done it yet: single-step through every line of your code.
Bonus exercise:
- Turn your algorithm into a generic routine that is suitable for a library; that is, support different value types (floating point types, integer types).