Monday, 23 June 2008

Examples of Illogical Comments

I recently bumped into the phrase "examples of illogical comments". The moment I read that, there immediately sprang into my mind terrifying visions of code from which I thought I had escaped...

'FORM-LOAD Event.
Private Sub Form_Load()

'Put BORDER Around Main FRAME.
Call ChangeBorder(fraContainer.hwnd, BDRSTYLE_RaisedLikeAButton)

'Position RESET Button.
cmdReset.Top = Me.ScaleHeight -
cmdReset.Height - 120
cmdReset.Left = Me.ScaleLeft + fraContainer.Left + fraContainer.Width - cmdReset.Width

'Position UPDATE Button.
cmdUpdate.Top = cmdReset.Top
cmdUpdate.Left = cmdReset.Left - cmdUpdate.Width - 120

'Ensure ESC Triggers CANCEL Button.
cmdReset.Cancel = True

'Set ACTIVATE-FIRST-TIME Flag.
mblnActivateFirstTime = True

'Initialise NUMBER And DATE CONTROLS.
Call InitialiseNumberDateControls

'Clear IGNORE-COMPUTE-SUMMARY.
mblnIgnoreComputeSummary = False

'Clear INCOME-CHANGED Flag.
mblnIncomeChanged = False

'Set ARRAYS-CLOSED Flag.
mblnCurrentArraysClosed = True
mblnOriginalArraysClosed = True
End Sub

No. No, no, no, no, no! Just no.

This is an example of some genuine code that I have had the pleasure of debugging. When every line suddenly becomes three times longer than it should, it makes it a whole lot more difficult to know what's going on. Oh, how we begged, how we pleaded with its author to change his style, but sadly, that leopard would not change its spots.

Much hair was lost around the building, I can tell you ;)

So, let's just set out a few general pointers, shall we?
  • Do not over-comment. It makes the program harder to read, and significant comments can get overshadowed by insignificant comments.
  • Code should be self-documenting. A line that says "mblnActivateFirstTime = True" does not need a comment to tell us we are setting the Activate First Time flag. We can see that. If you feel it needs a comment, tell us why we are setting the flag and how it is used. Do not state the bleedin' obvious.
  • If you write a comment, write it in English. Anyone should be able to understand it. For goodness sake, certainly don't write them in COBOL as appears to have happened here ;)

Code safely. And please, don't have nightmares. ;)

No comments:

Post a Comment