Tuesday, April 29, 2008

Beautifying SQL code

Boy, I must be sick.  The other day, for fun, I was reading a blog post on beautifying TSQL code in SQL Server.  Looking back over my brief stint as Yvonne's backup, I too shuddered when memories of those days flooded into my mind.

I have to agree with the author when he said that we are spoiled due to the formatting capabilities within Visual Studio.  Back in the old days, when computers were measured in terms of MHz, not GHz, a lot of the tools did not provide automatic formatting capabilities.  Instead, it was left up to the programmer, the human behind the keyboard, to manually alter the formatting in such a way that it was readable.  The company I used to work for actually had some very specific coding standards with regard to COBOL. 

  • The TO keyword in a MOVE statement was supposed to start in column 40
  • Paragraph names started with a 5 digit number and were ordered sequentially within the application
  • Constants within the application (ex. '3' or 'T') had to be removed and replaced with a working storage item

Within Visual Studio there are a number of formatting rules built in that make things easier to read for the majority of people.  For TSQL coding, however, we seem to have failed to understand that "neat" code is actually easier to read, easier to understand and easier to modify.  For instance, one of the most beneficial items is the indenting of blocks of logic so that they are set apart from the lines around them.  This helps you to identify all of the lines of code associated with an IF statement.  So why don't people do this?  Is it too hard to hit the tab key one more time?  Does RSI prevent you from using your left pinky?

Seeing a string of code with no indentation, no capitalization, no effort made to make the code readable is quite distressing.  One of the things I was taught at an early age (OK, 22) was that we are custodians of the code.  We do not own it, we modify it for our clients.  It is their code.  It is their application.  If I house sit for someone I don't go into their house and make a mess.  If I am looking after their pets, I don't take the cat litter and sprinkle it on the carpet.  So why would I write messy code and leave it behind for someone else to decipher and clean up?

No comments: