Friday, July 16, 2010

Code Review: .NET Coding Tip

I was doing a code review with a friend earlier this week and while we were discussing some application design topics, he noticed how I was coding calls to certain classes and offered a neat suggestion.  I'm far from a .NET guru, and am still constantly learning new syntax options since switching to C#, so this may be obvious to some/most .NET developers.

I often have classes that perform routine, discrete functions, such as getting preformatted dates, running regex routines, or querying SQL Server.  In the routine that my friend saw, I was using a standard data access class that I use for querying a GP database.

The following two lines create an instance of the "GP" class, and then call the ExecuteScalar method.  But he noticed that the GP instance was only being called once in my routine.

GP gp = new GP(gpUserID, gpPassword);
string result = gp.ExecuteScalar(database, CommandType.Text, commandText, sqlParameters);

He showed me the following syntax:

string result = new GP(gpUserID, gpPassword).ExecuteScalar(database, CommandType.Text, commandText, sqlParameters);

With this approach, you instantiate the class and call the method in one line.  Pretty slick.

This reminds me somewhat of how I sometimes add SQL a parameter directly to a command object and assign the value all in the same line.

sqlCmd.Parameters.Add("@param", SqlDbType.VarChar, 21).Value = "some value";

These types of tricks can sometimes dramatically reduce the number of lines required for a given operation.  I'm not a fan of compactness just for compactness' sake, but I do appreciate tricks that improve readability.

No comments: