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:
Post a Comment