Comment (computing)

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Dreftymac (talk | contribs) at 22:39, 28 December 2006 (typo). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

You must add a |reason= parameter to this Cleanup template – replace it with {{Cleanup|December 2006|reason=<Fill reason here>}}, or remove the Cleanup template.

In computer programming, a comment is a standardized way to embed information in the source code of a computer program. The structure, scope and processing applied to this information depends on the syntax and conventions of the specific programming language, as well as the intent of the developers.

Generally, comments are considered separate and distinct from source code:

  ProcessingPurpose
Source codeautomated via compiler or interpreter, and converted into object code; or otherwise translateddefines the structure of the program: (algorithms, datatypes, and namespaces)
Comments varies depending on context, may be processed or completely bypassed; or included only to be read by developersany of various purposes, including generating documentation, source code management or use in external programming tools

Types

There are generally two ways in which comments are indicated syntatically in source code: 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.

Some 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 //. Other languages support only one type of comment. For example, Ada comments are line comments: they start with -- and continue to the end of the line.

Regardless of the way in which comments are indicated syntactically, they may be used in two ways: as brief end-of-line comments to explain or document a single line of code, or as paragraph comments in which a block of text (usually spanning multiple lines) explains or documents something between two code statements. A common use for a paragraph comment is to explain in some detail what the following block of code statements does.

Usage

Comments can be used to summarise code or to 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 is 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 can 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 new or noteworthy approach to perform a certain task. Comments in this case can provide an explanation of the methodology. 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. Binary data may also be encoded in comments through a process known as binary to text encoding, although such practice is uncommon and typically relegated to external resource files.

In debugging, programmers will sometimes mark a code fragment as a comment, so that the code fragment will not be executed when the code is run. 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.

The typographical conventions for specifying comments varies widely. Additionally, individual programming languages sometimes provide unique variants. For a detailed review, please consult the programming language comparison article.

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.
15 REM It fills the screen with the word "WIKIPEDIA"
20 PRINT "WIKIPEDIA"
30 GOTO 20

Fortran 90

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Any non-numeric character in the first column comments out  *
*  the entire line.                                           *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

      PRINT "WIKIPEDIA" ! All characters after an exclamation
                        ! mark are an inline comment.
      END

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

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

See also

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

External links