Pages

Sunday, November 20, 2011

Massaging the Code

Lately I've had a project at work pick up and I've been working nearly every night. The majority of the project involved configuration of an application I already built some years ago. That part was easy. The rest of the work revolves around incorporating some mini programs that were written into my program and installing the whole thing at the client. The mini programs were written in .NET 1.0 by someone with limited coding experience. What that means is the code is 1. outdated 2. inefficient. I liken it to massaging the code. First I copy it all over as is and do the minimum needed to resolve any compilation errors. Then I rewrite obvious ugly code.

For Example:

Dim strSqlquery as String =""
Dim cmd as new SqlCommand()

strSqlquery = "SELECT somecolumn FROM sometable "
strSqlquery = strSqlquery & "WHERE somecolumn=1 "
strSqlquery = strSqlquery & "AND someothercolumn =' " & someVar & "'"

cmd.CommandText = strSqlquery

Becomes

Dim cmd as new SqlCommand("SELECT somecolumn FROM sometable WHERE somecolumn=1 AND someothercolumn = @aVar")

cmd.Parameters.Add("@aVar", varchar).Value = someVar

Technically they both do the same thing, but the second is better for a couple reasons. 1. Less variable declarations means less memory used and less processing. 2. Using parameters eliminates possible errors from building a dynamic query since that variable could be user entered and we don't know if they'll add special characters that need processing. using a parameter will process the content of the variable based on the type of parameter it is to eliminate those problems.

It seems as though we lose some readability by not breaking up the query but that can be remedied by using the & _ between breaks in the string, but that brings me to my third run through massage. 3. I remove all queries and put them into stored procedures. Using stored procedures organizes all your queries into a convenient location, faster execution of the query, and they can be changed if necessary in a live environment without having to cause interruptions with recompiling code.

If the first three massages don't get everything, the 4th step is to re-write objects into classes to group like functions and subroutines for readability. When all the massaging is done, the code is typically reduced in line by half and I can step back and say I'm proud to have had my hands on this code. I love programming!

1 comments:

Ricky Stephen LeBlanc, PMP said...

You are definitely a chip off the ole block. I can't stand inefficient code either. Your solution is much more effective.

Post a Comment