Monday, September 07, 2009

I'm sure it's been done before and I'm sure it will be done again.  Sometimes habits work to your advantage and sometimes they don't.

Here's a case where a habit bit me recently.

static void Main(string[] args)
{
    try
    {
        object dbConnection = GetDbConnectionWithRetry(0);
    }
    catch (Exception oneException)
    {
        Console.WriteLine("oneException=[" + oneException.ToString() + "]");
    }
}

private
static object GetDbConnectionWithRetry(int recursionCount)
{
    Console.WriteLine("GetDbConnectionWithRetry recursionCount=[" + recursionCount + "]");
    object dbConnection = null;
    if (recursionCount < 10)
    {
        dbConnection = OpenDbConnection();
        if (dbConnection == null)
        {
            dbConnection = GetDbConnectionWithRetry(recursionCount++);
        }
    }
    return dbConnection;
}

private
static object OpenDbConnection()
{
    // This is just a dummy method for sample code purposes
    return null;
}

It's humorous in retrospect.  Can you spot the bug?  What habit should I break myself of?

9/7/2009 3:22:02 AM (Central Standard Time, UTC-06:00)  #    Disclaimer  |  Comments [1]  | 
9/7/2009 3:01:02 PM (Central Standard Time, UTC-06:00)
I'm guessing by the title that the problem you ran into is infinite recursion, so I expect the bug arises from the use of post increment which will not evaluate until after the function returns, which it never will (infinite recursion until stack overflow).

In this case, there's no reason for the recursionCount field to be mutable at all, so recursionCount + 1 is probably better form anyway.

I see a few other things I'd do differently as well, but I don't think they're the ones you are intending to highlight here.
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):