Wednesday, July 26, 2006

Generics + Bad Idea Jeans

{

I can't get the Bad Idea Jeans SNL sketch out of my head, but I'm not sure I trust myself. At the request of a coworker, I wrote the following to show how a generic Dictionary could be returned from a method with underlying types for key/value stated ahead of time:




public static Dictionary<X, G> BuildDictionary<X, G>(string cmd, string keyColumn, string valColumn) {
Dictionary<X, G> myDictionary = new Dictionary<X, G>();
SqlDataReader rd = new SqlCommand(cmd, GetConnection()).ExecuteReader();
while (rd.Read()) {
myDictionary.Add((X)rd[keyColumn], (G)rd[valColumn]); // ? good idea?
}
rd.Close();
return myDictionary;
}




It leverages generics to define the returned dictionary so that a call could be made like this:




Dictionary<int, int> data = DBDictionary.BuildDictionary<int, int>("myproc", "key", "val");




Perhaps I'm paranoid, or I've been burned too much, or I'm not scared of a little type dynamism, but this seems like a Bad Idea. The big reason, of course, is the casting that goes on in the method:

myDictionary.Add((X)reader["someField"], (G)reader["someField"]);

Reasons for my anxiety?
1. What if the underlying field has a change of type? You won't know until runtime when things blow up.
2. Maintenance if underlying field type does, in fact, change. If being type specific is avoided, you can gracefully accept these changes without a recompile. Even if your lookup (what's in the dictionary) is used, if it's passed to a SqlCommand as a parameter (which is the way I normally do it), the reference it expects is to an object type as in:

SqlParameter para = new SqlParameter("@Foo", objectRef);

3. I'm not afraid of strings. Over time I've been more reluctant to convert things, especially numbers. For example, if a numeric value is passed in the querystring, like:

http://myserv/Page.aspx?custId=101

Why should we convert custId to a numer if it's going to be passed to a parameter (see code above)? Another scenario is when some underlying value is going to end up in a textbox. I do not fear the string, just the Convert.ToXXYYZZ code I'd have to type out if I did want to be "type safe."

But some may feel differently, especially the ones who think that if something in the database changes you may want to intentionally have your code break so that you're aware of it. That's the only idea besides premature optimization that I can use to justify this approach...

}

No comments: