Prime Factors Kata in C#

Ever since I heard about the concept of “code kata”, I’ve been practicing them every day.

If you hadn’t heard, code kata are lot like those in martial arts. They are an exercise wherein you make the same decisions over and over again so that you are more likely to make those same decisions again when under stress. Since TDD is a somewhat rigid process where the same rules are followed over and over again it lends itself to this concept of “kata”.

There are a couple of kata that I do. First, the “calculator kata” (thanks Andrew Woodward), where you create a class with a method that sums all of that numbers in a comma delimited string.

Second, and more fun, is a kata where you write a method to return a list of all of a number’s prime factors. I first learned about this kata from Uncle Bob Martin. A few days ago he mentioned on Twitter that he was trying to get a screencast of a “flawless” version of this kata. After about 30 attempts, I did not achieve “flawless”, but I think I achieved “pretty good”.

This first video shows the primary kata exercise. Using TDD, I steadily create a method called Generate that lists the prime factors for an input integer. I also use Resharper and its templating and refactoring features to make this process easier. As an aside, if you are not presently using something like Resharper or CodeRush to help you as you code, you are definitely doing things the hard way.

In the video, I try to rigidly adhere to the TDD method:

  1. Write a test first
  2. Watch it fail
  3. Write just enough code to make it pass
  4. Verify the test passes
  5. Refactor

On that note, I know it annoys people to no end when I hard-code return values when I know I’ll be eliminating that code very shortly. But it’s neat to watch how the algorithm transforms over the course of the kata, and you wouldn’t see it if you didn’t follow the steps rigidly.

View Kata Screencast #1

This second video is not part of the kata, but it’s meant to show two things:

  • Refactoring the code and using your existing tests to validate that you haven’t broken anything. I call this the “real coder” refactoring since it replaces the easy-to-read while loops with not-so-easy-to-read for loops.
  • The use of MbUnit’s “Row” tests that we can use the same test code to validate multiple inputs to the validator.

View Kata Screencast #2