共用方式為


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.

If you follow the guidelines discussed so far in this chapter, you are using a naming convention that identifies objects, variables, constants, and procedures, and you are using a prefix to indicate each variable's data type and scope. In addition, you are using white space, line breaks, and indentation to make your code easy to read and to create a visual representation of the code's logic. In other words, you have taken full advantage of all of the benefits that use of a consistent naming convention and structured code will yield. To a large degree, you should now be able to tell how your code is working just by looking at it.

The purpose of adding comments to code is to provide a plain English 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 simply restate what is already obvious add nothing to the code and should be avoided. In addition, exactly how the code works may change as it gets updated or revised. 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 need to 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. Beginning 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

As you can see, these comments add nothing that isn't already evident from the code itself. Now take a look at 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

The SaveStringAsTextFile procedure is available in the modAdditionalSamples module in FormattingExamples.doc in the ODETools\V9\Samples\OPG\Samples\CH03 subfolder on the Office 2000 Developer CD-ROM.

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 needed, 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 they apply to. Insert comments before the line or block of code they apply to, not on the same line as the code itself.

In certain circumstances you will also use comments to document the arguments passed to a procedure, whether those arguments should be within a certain range of values, whether global variables are changed within the procedure, and 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.

You should make it your practice to write comments at the same time that (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. Never "save it for later," because there will often never be time to do it later, or if there is, you will not understand the code as well when you come back to it at some other time.

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 necessary. 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 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. This is rarely the behavior you want. The correct way to format script so that 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 will need to 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>

The preceding code fragment is available in ScriptGoodFormatting.htm in the ODETools\V9\Samples\OPG\Samples\CH03 subfolder on the Office 2000 Developer CD-ROM.

For more information about writing script in HTML pages, see Chapter 12, "Using Web Technologies."