This blog is not just about coding in SQL Server. It's also about the data access client. This post is for all you VB.NET and C# developers who are former VB programmers. Having worked with VB since its early days, there were many times when I had wished I could do overload functions and make for a nicer, more respectable interface.
Now I had resisted .NET at first; I didn't think the return on investment for learning C# or VB.NET was worthwhile. Why make the change? I am glad I dug into this technology because not only does my world now revolve around it, but also because it's just so much better.
For example, in the following pseudo-code, I have the overloaded GetRecord method. The two public methods take either a String or Int32, representing, respectively, the Description or ID of the record I am trying to fetch. The private method takes only a SqlCommand object that is created in the other two public methods.
public DataSet GetRecord(String Description)
{
SqlCommand sqlCmd = new SqlCommand("prGetRecordByDescription", this.dbConnection);
sqlCmd.Parameters.Add(new SqlParameter("@Description", (Object)Description));
return (GetRecord(sqlCmd));
}
public DataSet GetRecord(Int32 RecordID)
{
SqlCommand sqlCmd = new SqlCommand("prGetRecordByID", this.dbConnection);
sqlCmd.Parameters.Add(new SqlParameter("@RecordID", (Object)RecordID));
return (GetRecord(sqlCmd));
}
private DataSet GetRecord(SqlCommand sqlCmd)
{
SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlCmd);
DataSet ds = new DataSet("MyDataSet");
Int32 ret = dbAdapter.Fill(ds, "MyDataSet");
return (ds);
}
The code is simple, clean, elegant. I'm sure there are some VB junkies who are thinking “I could do this using optional parameters and keep the code in a single procedure.” You are right - heck, I've done just that many, many times. It's just that this code is so much nicer. For example, when examining the object, the object browser would show the method twice, once with the RecordID Int32 parameter and once with the Description String parameter. It's practically self documenting. The VB method would appear once with two optional parameters. Meaning, none, either or both could be passed. So, since both parameters are optional, you would have to write additional code to check for the undesired conditions, such as neither parameter being passed and both being passed.
Why am I writing about this. I believe ther are many VB developers making the switch to .NET and I want them to be aware that they have new choices when it comes to writing code and accessing data. VB folks - I'm here for you!