The prime factors kata, as described by Uncle Bob , contains **deep lessons** that can be learned by approaching it several times.

Here you can see one of my solutions:

Prime factors kata from Carlos Ble on Vimeo.

The first time I solved the kata, it was very easy. I test-drove it very close to the video. A couple of days later I was the facilitator in a coding dojo and asked the folks to practice this kata. Dojo attendees couldn't accomplish the constraint of "**don't use any loop until you have 4 green tests**" that I proposed to them. At the end of the dojo I started coding the solution and I couldn't find an easy way to accomplish my own rule. I didn't finish the demo on time. So I started wondering why the process didn't work this time.

Very interesting lessons have been learned from this:

- Don't forget to
**triangulate depth-first** - Are you sure you can't
**refactor**by now?

- If the problem seems to be an algorithm,
**choose a high level strategy**before starting coding

In my demo, I wasn't very focused so I said to myself... "don't think, just embrace the TDD rules and go for them", so I started test-driving. The problem is that I didn't triangulate deph-first. I started jumping from one scenario to another but not finishing any of them. So I couldn't see a right way to refactor towards generalization. The code didn't tell me how to factor out towards the algorithm.

Even if you don't see the right triangulation, you must take the time to see what can you refactor. Bad triangulation scenario:

def factorize(number): result = [2] if number % 2 == 0: result = [2] if number == 3: return [3] if number == 4: return [2,2] if number == 6: return [2,3] return [2]

Even with this code, if you take to time to find out similarities, you can see that number 2 is a prime factor for others so that you can refactor:

def factorize(number): result = [2] if number % 2 == 0: if number != 2: return [2, number / 2] if number == 3: return [3] return [2]

From here, you can still success test-driving the algorithm.

I realized that it was easy for me the first time because I did choose a mental strategy before coding which was... "*a number is prime if all the numbers below it can not divide it*", which already was a loop strategy.

Here you can see a nice different by Angel Nuñez Salazar.

Thanks to all dojo attendees for their feedback 😉

Pingback: Wrong generalization « El blog de Carlos Ble()