Comment (computing)

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Dreftymac (talk | contribs) at 19:02, 1 December 2006 (→‎Other uses: minor copy edit ;; links). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In computer programming, a comment is a programming language construct that provides a mechanism for embedding information in the source code that is (generally) ignored by compilers and interpreters but may be of use to people reading the program source, or other programming tools that process the source such as documentation generators or source code management systems.

Some people believe that comments are unnecessary because code should be written in a way that makes it self explanatory (it is not uncommon to encounter source code that contains no comments); other people believe that source code should be extensively commented (it is not uncommon for over 50% of the non-whitespace characters in source code to be contained within comments).

Types

There are generally two types of comments: block comments and line comments.

Block comments are delimited by a sequence of characters that mark the start of the comment and continue until the sequence of characters that mark the end of the comment. Block comments are allowed to span multiple lines of the source code. Typically, block comments do not nest, so any comment start delimiter encountered within a comment body is ignored. Some languages allow nested block comments to facilitate using comments to comment-out blocks of code that may itself contain block comments.

Line comments on the other hand either start with a comment delimiter and continue until the end of the line, or in some cases, start at a specific column (character line offset) in the source code and continue until the end of the line.

Many programming languages employ both block and line comments with different comment delimiters. For example, C++ has block comments delimited by /* and */ that can span multiple lines and line comments delimited by //.

Usage

Comments could summarise code or explain the programmer's intent. This is called the why rather than how approach. The two are often close, but not always. According to this school of thought, restating the code in plain English may be a waste of time; the need to explain the code may be a sign that it is too complex and should be rewritten.

"Don't document bad code – rewrite it" (The Elements of Programming Style, Kernighan & Plauger).
"Good comments don't repeat the code or explain it. They clarify its intent. Comments should explain, at a higher level of abstraction than the code, what you're trying to do." (Code Complete, McConnell)

Comments could also be used to guide a new programmer through source code that performs some task. In this case almost every line could be commented. New programmers can gain much insight in various branches of programming and computer science by reading through extensively commented source code. Typical things that could be commented on are function calls and arguments, algorithms used, and caveats.

Sometimes a programmer thinks up a neat trick to perform a certain task. Comments could in this case provide an explanation of the trick used. Although the why rather than how approach discourages such comments, sometimes an explanation is just what is needed to make a future programmer understand what a certain piece of source code is doing. This might especially be true in the case of rarely-used optimizations, constructs or function-calls. For example, a programmer may add a comment to explain why an insertion sort was chosen instead of a quicksort, as the former is, in theory, slower than the latter. This could be written as follows:

list = [f (b), f (b), f (c), f (d), f (a), ...];
// Need a stable sort. Besides, the performance really does not matter.
insertion_sort (list);

Comments may also be used to explain why a block of code does not seem to fit conventions or best practices. This is especially true of projects involving very little development time, or in bug fixing. For example:

 ' Second variable dim because of server errors produced when reuse form data. No
 ' documentation available on server behavior issue, so just coding around it.

Logos, diagrams, and flowcharts consisting of ASCII art constructions can be inserted into source code formatted as a comment. Additionally, copyright notices can be embedded within source code as comments.

In debugging, programmers will sometimes mark a code fragment as a comment, such that the program will not compile or interpret it. This is called commenting out the fragment.

Styles

Comment styles are often agreed upon before a project starts. Usually programmers prefer styles that are easy to modify and difficult to break.

For example, C-style comments could look like this

/*

    This is the comment body.

*/

or maybe this

/***************************\
*                           *
* This is the comment body. *
*                           *
\***************************/

If a programmer's editor doesn't manage the second variant automatically, it may discourage changes to the comments, thus leading to comments which are out of date with respect to the code. On the other hand, the visibility of the second comment variant is much higher.

Some people, such as Allen Holub (in his book Enough Rope to Shoot Yourself in the Foot, ISBN 0-07-029689-8, 1995, McGraw-Hill), advocate aligning the left edges of comments:

/* This is the style recommended by Holub for C and C++.
 * It is demonstrated in Enough Rope, in rule 29.
 */
/* This is another way to do it, also in C.
** It is easier to do in editors that do not automatically indent the second
** through last lines of the comment one space from the first.
** It is also used in Holub's book, in rule 31.
*/

Different styles can be chosen for different areas of code, from individual lines to paragraphs, routines, files, and programs. If the syntax supports both line comments and block comments, one approach is to use line comments only for minor comments (declarations, blocks and edits) and to use block comments to describe higher-level abstractions (functions, classes, files and modules).

Certain projects try to define rules like "one comment every ten lines". They can be counterproductive when adhered to with too much rigor, but might still be of use when one wants to quickly judge after writing a body of code whether one needs to check if enough comments are in place.

Automatic documentation generation

Some programming tools can read structured information in comments in order to generate documentation automatically. Automatic documentation generation from the comments in the source code allows the documentation of the interface and use of the code to be maintained in the source file with the code, but to be viewed in independent stand-alone documentation. Keeping the documentation close to the code makes it easier, and thus more likely, to keep the documentation up to date with changes in the code.

Examples of documenation generators include the javadoc program, designed to be used with the Java programming language, Ddoc for the D programming language and doxygen, to be used with C++, C, Java, IDL and others.

C# implements a similar feature called "XML Comments" which are read by IntelliSense from the compiled .NET assembly. The next revision of Visual Basic will also feature this.

Other uses

Developer tools sometimes store metadata in comments, such as insert positions for automatic header file inclusion, commands to set the file's syntax highlighting mode, or the file's revision number. These functional control comments are commonly referred to as annotations.

Examples

Comparison

See main article: Programming Language Comparison: Comments.

In-context

C

/*
 * Check if we are over our maximum process limit, but be sure to
 * exclude root. This is needed to make it possible for login and
 * friends to set the per-user process limit to something lower
 * than the amount of processes root is running. -- Rik
 */
if (atomic_read(&p->user->processes) >= p->rlim[RLIMIT_NPROC].rlim_cur
    && !capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RESOURCE))
    goto bad_fork_free;

(This is from the fork.c file from the Linux kernel source)

Classic BASIC

10 REM This is a classic BASIC program for novice programmers.
20 PRINT "WIKIPEDIA"
30 GOTO 20

Java

/**
 * Registers the text to display in a tool tip.   The text 
 * displays when the cursor lingers over the component.
 *
 * @param text  the string to display.  If the text is null, 
 *              the tool tip is turned off for this component.
 */
public void setToolTipText(String text) {

(from the Sun Microsystems javadoc documentation; the comment is designed to be read by the javadoc processor)

Visual Basic

'
' Cut off HKEY_USERS\ if present.
' This makes interoperating with regedit easier.
'
If Len(SIDstring) > 11 Then
    If Left(SIDstring, 11) = "HKEY_USERS\" Then
        SIDstring = Mid(SIDstring, 12)
    End If
End If

'
' Open the WMI Service and retrieve the SID
'
On Error Resume Next
Set SIDobject = GetObject( _
    "winmgmts:{impersonationLevel=Impersonate}" _
    ).Get("Win32_SID.SID='" & SIDstring & "'")
If Err Then
    MsgBox "Could not retrieve the SID.", vbOkOnly, "Sorry"
    Exit Do
End If

(Adapted from an example illustrating ways to create system administration tools.)

Windows PowerShell

# Displays a message in a dialog box, waits for the user to click a button,
# and returns a value indicating which button the user clicked.
#
$obj = New-Object -ComObject wscript.shell
$result = $obj.popup("Hello World!", 0, "Wikipedia Message Box", 1)

See also

  • Docstring, a specific type of comment that is parsed and retained throughout the runtime of the program

External links