Share via


Using Comments Effectively

This content is no longer actively maintained. It is provided as is, for anyone who may still be using these technologies, with no warranties or claims of accuracy with regard to the most recent product version or service release.

The purpose of adding comments to code is to provide an understandable description of what your code is doing. Comments should provide information that is not otherwise available from reading the code itself. Good comments are written at a higher level of abstraction than the code itself. Comments that only restate what is already obvious add nothing to the code and should be avoided. In addition, if your comments speak to how the code works, instead of to what it does, you have created an additional code-maintenance problem, because comments that describe how code works must be revised whenever you change the code. Failing to maintain these comments along with the code creates a risk that the comments will no longer describe the code. Some developers often write "how" comments that merely restate what is already obvious from the code itself; for example:

' Make sure the length of strSource is not zero and it contains
' a ".txt" extension.
If Len(strSource) > 0 And InStr(strFileName, ".txt") > 0 Then
   ' If strSource does not contain a ":" or a "\" then
   ' return False.
   If InStr(strFileName, ":") = 0 Or InStr(strFileName, "\") = 0 Then
      SaveStringAsTextFile = False
   Else
      ' Get the next available file number.
      intFileNumber = FreeFile
      ' Open the file in Append mode.
      Open strFileName For Append As intFileNumber
      ' Write data to the file on disk.
      Print #intFileNumber, strSource;
      ' Close the file.
      Close intFileNumber
   End If
Else
   ' Return False.
   SaveStringAsTextFile = False
End If

These comments add nothing that is not evident from the code itself. The following is the full version of this procedure that lets the code speak for itself and uses comments that describe only what the code is doing:

Function SaveStringAsTextFile(strSource As String, _
                              strFileName As String) As Boolean

   ' Save the string in strSource to the file supplied
   ' in strFileName. If the operation succeeds, return True;
   ' otherwise, return False. If the file described by
   ' strFileName already exists, append strSource to any
   ' existing text in the file.
   
   Dim intFileNumber As Integer
   
   On Error GoTo SaveString_Err
   
   ' Assume that the operation will succeed.
   SaveStringAsTextFile = True
   
   If Len(strSource) > 0 And InStr(strFileName, ".txt") > 0 Then
      If InStr(strFileName, ":") = 0 Or InStr(strFileName, "\") = 0 Then
         ' Invalid file path submitted.
         SaveStringAsTextFile = False
      Else
         ' Save file to disk.
         intFileNumber = FreeFile
         Open strFileName For Append As intFileNumber
         Print #intFileNumber, strSource;
         Close intFileNumber
      End If
   Else
      SaveStringAsTextFile = False
   End If
   
SaveString_End:
   Exit Function
SaveString_Err:
   MsgBox Err.Description, vbCritical & vbOKOnly, _
       "Error Number " & Err.Number & " Occurred"
   Resume SaveString_End
End Function

At a minimum, you should add comments at the module level to describe the group of related procedures in the module. Add comments at the procedure level to describe the purpose of the procedure itself. For example, the following module-level comments document the public and private procedures (called "methods" in a class module), the properties and their data types, and information about how to use the class as an object:

' This class provides services related to creating and sending
' Outlook MailItem objects. It also includes wrappers to handle
' attaching files to a mail message.
'
'   Public Methods:
'      MailAddRecipient(strName As String, Optional fType As Boolean)
'         strName:   Name of recipient to add to message.
'         fType:      Outlook MailItem Type property setting.
'      SendMail(Optional blnShowMailFirst As Boolean)
'         blnShowMailFirst:   Whether to show the Outlook mail message
'                           before sending it. Set to True 'programmatically
'                           if unable to resolve recipient addresses.
'
'   Private Methods:
'      InitializeOutlook()
'      CreateMail()
'
'   Public Properties:
'      MailSubject:         (Write only, String)
'      MailMessage:         (Write only, String)
'      MailAttachments:   (Write only, String)
'
'   Usage:   From any standard module, declare an object variable of type
'         clsMailMessage. Use that object variable to access the methods
'         and properties of this class.

Where appropriate, add comments to describe the functionality of a particular line or block of code. These comments should be used sparingly and should be used to document any unusual aspects of the code. A blank line should precede all comments, and they should be aligned with the code to which they apply. Insert comments before the line or block of code to which they apply, not on the same line as the code itself.

In certain circumstances, you will use comments to document the arguments passed to a procedure, to state whether those arguments should be within a certain range of values, to convey whether global variables are changed within the procedure, and to relate the procedure's return values. It is not unusual to include comments that document a procedure's revision history, the names of other procedures that call the current procedure, the author of a procedure (or a revision), or a sample syntax line showing how the procedure is called.

It is a good practice to write comments at the same time (or earlier than) you write your code. Some developers write the comments for all of their procedures before they write a single line of code. It can be very effective to design procedures using only comments to describe what the code will do. This is a way to sketch out a framework for a procedure, or several related procedures, without getting bogged down in the details of writing the code itself. Later, when you write the code to implement the framework, your original high-level descriptions can be effective comments. Whatever technique you use, always enter or revise your comments as soon as you write the code. Avoid "saving it for later," because there is rarely time to do it later, or, if there is, you will not understand the code as well when you come back to it.

You add comments to an HTML page by wrapping them in comment tags. The HTML element for a comment is the <!— and —> tag pair. At a minimum, add comments to document the HTML where appropriate. Use an introductory (header) comment to document each subroutine and function in the HTML page. How you add comments to script in an HTML page depends on the scripting language you are using. In VBScript, comments are indicated by an apostrophe (') character. In Microsoft® JScript®, you use either //, which indicates that the rest of the line is a comment, or /* comment text */, which indicates that all of the comment text is a comment, no matter how many lines it spans.

Comments serve an additional purpose when they are used in script in an HTML file. Browsers will ignore any unrecognized HTML tag. However, if the script tags are ignored, the browser will attempt to render the script itself as plain text. The correct way to format script so older browsers will ignore both the script tags and the script itself is to wrap your script (but not the script tags) in the <!— and —> comment tags. If you are using VBScript, you must use the apostrophe character to add comments to script that is nested within the <!— and —> comment tags. The following example uses both forms of comment tags:

<SCRIPT LANGUAGE="VBSCRIPT">
<!--
   Option Explicit

   Sub UpdateMessage()
      ' This procedure calls code in a scriptlet to get 
      ' values for the current day, month, and year, and then
      ' uses the innerHTML property of a <DIV> tag to dynamically 
      ' display those values on the page.

      .
      .
      .
-->
</SCRIPT>

See Also

Commenting Code | Automating Code Commenting | Using Web Technologies