TDD Day 3

Published on: January 6, 2014

I started the next kata at Coders Dojo. I think you're supposed to do katas over and over again, but I didn’t think I'd gain that much from repeating the FizzBuzz kata from yesterday. Maybe when I've got a better hang of things I can go back to FizzBuzz and learn something from it. Anyways, today’s exercise was new to me - finding all the prime factors for a given number. Of course I've done this in math class, but I haven’t written a program for it before.

I figured I shouldn’t have a list of all the primes ever (also, not possible to do...), and that calculating the primes on the fly would be too slow. (Not that there’s a time constraint, just that I know computers spend their lives computing the next prime number and it seemed a bit in efficient.) Fortunately Ruby has a Prime class, so I borrowed that one. I’m not sure this was in the spirit of the kata, but TDD and Agile are all about writing as little code as possible, and I thought using someone else’s code would further that cause. Looking back I’m not so sure...

I went through the exercise and got it all sorted. I'll admit I'd forgotten 1 isn’t a prime number, but a bit of Googling set me straight. In the end the Prime class wasn’t as helpful as I'd thought since it didn’t come in the “correct” form as described in Coders Dojo. So I had to write a converting function to deal with this.


When I was done I found a “solution” posted by the Dojo. It was... much better than mine. :( Well, I guess that’s what learning is all about. I ended up putting similar tests together (a few primes and a few composite numbers all in one “it” block). I’m pretty sure you're not supposed to do this, but I really haven’t found a good reason why not. But I only had a few test cases, the solution had many more. The solution also rolled its own factorization rather than relying on Prime. I had assumed this would be too slow, but of course that was premature optimization. No one else is going to use this function, just me and my tests. Time is unimportant. Also, I have no idea how the Prime class works, it might compute the primes on the fly itself.

All in all, I think I did better sticking with the TDD mindset, but I'd like to come back to this one in a little while (once I've forgotten it a bit), and write my own factorization without leaning on Prime.

comments powered by Disqus