WTF: The Exceptional Connection

Tuesday November 14thWTF Category

This would have to be close to the dumbest way of verifying the state of a connection :) Well, that might not be true, but it’s definitely one of the dumbest ways.

This is a funky snippet of code that was extracted from a system I’m doing some work on at the moment:
[source:csharp]public static bool IsValid(OracleConnection conn)
{
OracleCommand cmd = new OracleCommand(”select 1 from dual”, conn);
cmd.CommandType = CommandType.Text;
cmd.ExecuteReader();
cmd.Dispose();
return true;
}[/source]So, if it doesn’t hurl an exception at you, it’s valid! Nice work eh? So if you have to check for exceptions anyway, why not just try using the connection in the first place and handle THAT exception instead?

*shudders*

WTFness: 9 / 10

2 Comments

  1. Keef
    November 14, 2006

    I’m not an Oracle coder, but I understand that this code takes in a connection and attempts to run a dummy select command on it. If nothing throws, return true.

    Yikes!!! Sledgehammer to do a scalpel’s work anyone? I’m sure there’s probably a simple API call to ping the connection to check it’s working.

    On the subject of exception handling, it’s something that a lot of people don’t know well enough (myself included :-( ). I think part of the reason for this is that it tends to be something taught towards the end of whatever books or courses people learn to code from, and therefore people are already in the habit of exception free coding by that point.

  2. OJ
    November 15, 2006

    Well, basically what you should do is something like this:

    if( conn.State == System.Data.ConnectionState.Open )
    {
        // do stuff
    }

    Hardly rocket science! The code really has a huge WTF. This particular type of check shouldn’t have to deal with exceptions at all, it just needs to query the state of the object.

Leave a comment

Size

Colors