Jump to content

Comment (computing): Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
rv: Article is about comments in programming languages, not general computing; perhaps two different articles are needed
m moved MediaWiki talk:Comments to Comment (computing) over redirect: revert
 
(31 intermediate revisions by 12 users not shown)
Line 1: Line 1:
#REDIRECT [[Comment (computer programming)]]
{{cleanup-date|December 2006}}

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 [[compiler]]s and [[Interpreter_%28computing%29|interpreters]] but may be of use to people reading the program source, or other [[programming tool]]s that process the source such as [[Documentation_generator|documentation generators]] or [[Source_Code_Management|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_%28computer_science%29|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 [[Delimiter#Bracket_delimiters|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 [[delimiter]]s. For example, [[C++]] has block comments delimited by <code>/*</code> and <code>*/</code> that can span multiple lines and line comments delimited by <code>//</code>.

==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 &ndash; rewrite it" (''[[The Elements of Programming Style (book)|The Elements of Programming Style]]'', [[Brian Kernighan|Kernighan]] & [[P. J. Plauger|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]]'', [[Steve McConnell|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 new or noteworthy approach to perform a certain task. Comments could in this case 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.

[[Logo]]s, 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, 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)|Java programming language]], [[Ddoc]] for the [[D programming language]] and [[doxygen]], to be used with [[C++]], [[C (programming language)|C]], Java, [[Interface description language|IDL]] and others.

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

==Other uses==

[[Programming_tools|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 control|revision number]]. These functional control comments are commonly referred to as [[annotation]]s.

==Examples==
===Comparison ===
:''See main article: [[Comparison_of_programming_languages_%28syntax%29#Comments|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 [[Comparison_of_programming_languages_%28syntax%29#Comments|
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 <code>fork.c</code> 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==

* [http://dkrukovsky.blogspot.com/2005/07/how-to-write-comments.html How to Write Comments] by Denis Krukovsky
* [http://java.sun.com/j2se/javadoc/writingdoccomments/ How to Write Comments for the Javadoc Tool]
* [http://www.stack.nl/~dimitri/doxygen/index.html Doxygen, a documentation system for C, C++, Java, Objective-C, Python, IDL and to some extent PHP, C#, and D]

[[Category:Source code]]
[[Category:Articles with example C code]]
[[Category:Articles with example Java code]]
[[Category:Articles with example Visual Basic code]]


[[da:Kommentar]]
[[de:Kommentar (Programmierung)]]
[[fr:Commentaire (informatique)]]
[[ja:コメント (コンピュータ)]]
[[pl:Komentarz (informatyka)]]
[[ru:Комментарии (программирование)]]

Latest revision as of 08:04, 24 January 2011