Factorial Bug Hunt

by Andy Masters 25. March 2011 16:06

I was playing around with TDD again. It highlighted to me just how bad a very simple and correct looking function can be.

In maths, Factorial(n) is written n!, so Factorial(10) is the same as 10!.

1! =1
2! =1*2=2
3! =1*2*3=6
n! = n * n-1 * n-2 * ... * 1

I wrote this function without TDD to calculate the nth Factorial number recursively:


public static long FactorialRecursive(int index)
{
   if (index==1)
   {
      return 1;
   }
   return index * FactorialRecursive(--index);
}

I then rewrote the function using TDD. I discovered 4 quite serious bugs in the above code, see if you can find them (answers in my next post, although I expect there will be others that I've missed too). I also tried a radically different approach to writing the function, how would you write it?

 

The benefit of unit-testing is that seemingly correct code should get smoked out.

The benefit of TDD is you get a better design, and just enough tests to prove it is correct.

 

 

Tags:

Development | Ideas | Testing

Comments

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen