Prime factors kata
The prime factors kata is popularised by Uncle Bob (Robert C. Martin). He is well known for his championing of Test Driven Development (TDD) and clean code. Uncle Bob often uses the prime factors kata to explain the power of TDD. The kata is interesting, because it shows the power of incremental steps. Every test you introduce will fine tune the algorithm until finally a working factorisation algorithm emerges. If you follow the rules of TDD it can sometimes feel as if the algorithm arrives out of thin air.
I would recommend performing this kata yourself before you continue reading. The best way to do the kata is by taking incremental steps like this:
- The number 1 returns an empty list of factors
- The number 2 returns a list with the factor 2
- The number 3 returns a list with the factor 3
- The number 4 returns a list of the factors 2 and 2
- Etc
For every new number you only make the minimum changes to pass the test. After a few steps you will notice the algorithm becomes better and better and more and more tests start passing without any code changes. You can follow these steps until a fully working algorithm emerges.
If you have no experience with TDD, I would recommend to read the introduction article: Test driven development: red, green, refactor. After trying the kata you can continue in this article to see how I would solve the kata.