Tuesday, December 4, 2007

Overcoding

One of the goals of this site is to help you write better, more efficient code. To that end, I invite you to consider the following code.
Public Function buildSQLStatement() As String
   Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder
   sb.Append("SELECT * FROM X_TABLE ORDER BY X_FIELD_1")
   Return sb.ToString
   sb = Nothing
End Function
Now, I am a big fan of .NET's StringBuilder class. I have used alternative methods to string concatenation ever since the days of VB5 and Classic ASP, rather than the clunky (and painfully-slow) "thisString = thisString & someOtherString" approach. I suspect whoever wrote the function above had this principle in mind when they wrote this function, so they should get at least a point or two for using the StringBuilder class.

However, they do not get points for efficiency on this particular function. This is a classic example of what I call "overcoding" -- which means exactly what you think it means.

Have you ever read a book (I highly recommend anything by Dean Koontz) and after pages of descriptions of scenery and flowers and landscape, you were ready to scream "Enough already! Get to the point!"? Have you? That, my friends, is overwriting, and it is as exasperating to me as overcoding.

So, let's get to the point, shall we? Here's the new code:
Public Function buildSQLStatement() As String
   Return "SELECT * FROM X_TABLE ORDER BY X_FIELD_1 "
End Function
Nothing sexy going on here -- just tight, efficient code.

The moral of the story?

Don't overthink what you're doing. Write code that does what it needs to, and no more. If you need to explain what's going on, use a comment. And yes, use StringBuilder when it's needed, and don't when it's not. The best intentions in the world won't make your code run faster. Please, stop overcoding.

NOTE: Even though the function itself has been optimized, there's STILL a potential problem here. Can you spot it? I will address it in my next post.

No comments: