Sunday, July 18, 2010

Tame that recursive code

If college has taught me anything by now, it's certainly not writing practical real world - ready code.
As an example, let's take the widely accepted academic presentation on recursion.
The first thing that comes to mind to most students or fresh graduates when they think of recursive code is the classic 'Recursive Factorial'. It's supposed to provide them with an easy introduction to the capabilities of using recursion in your code.
So what you end up with is something like this:
public int RecursiveFactorial(int value)
{
    if(value != 0)
    {
        return value * RecursiveFactorial(value - 1);
    }
    else
    {
        return 1;
    }
}
Now that's all fine if you have no practical common sense at all. A much better piece of code would be:
int finalValue = 1;
for(int i = 2; i <= value; i++)
{
    finalValue *= i;
}
I'm sure everyone can agree that this is a much better way of doing things. Some might say that the purpose of the RecursiveFactorial method is not a best practices guide, but to gently show would-be developers what a recursive method can do. But that's just like teaching 7'year olds how to read using Lorem Ipsum quotes. To conclude, i'm definitely not saying that you should ditch recursion altogether, it's a great tool when used wisely. But always keep in mind that, if you have more than one option, the non-recursive one is almost always the quickest.

No comments:

Post a Comment