An illustration of Javasource code with 'prologue' comments indicated in red and 'inline' comments in green. 'Program code' is in blue.
In computer programming, a 'comment' is a programming language construct used to embed information in the source code of a computer program. In most cases,[1] when the source code is processed by a compiler or interpreter, comments are ignored.[2]
Comments have a wide range of potential uses: from augmenting program code with basic descriptions, to generating external documentation.[3] Comments are also used for integration with source code management systems and other kinds of external programming tools.
The flexibility provided by comments often allows for a wide degree of variability and potentially non-useful information inside source code. To address this, many technical commentators and software analysts often subscribe to any of several "philosophies" and guidelines regarding the proper use of comments.
Source code can be divided into ''program code'' (which consists of machine-translatable instructions); and ''comments'' (which include human-readable notes and other kinds of annotations in support of the program code).[4] The syntax and rules for these are usually defined in a programming language specification.
Comments are generally formatted as ''block comments'' (also called ''prologue comments'') or ''line comments'' (also called ''inline comments'').[5]
Block comments delimit a region of source code in which the region is allowed to span multiple lines. This region is specified with a ''start'' delimiter and an ''end'' delimiter. Some programming languages (such as MATLAB) allow block comments to be recursively nested inside one another, but others (such as Java) do not.[6][7][8]
Line comments 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.8
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.8
Uses
How best to make use of comments is subject to dispute; different commentators have offered varied and sometimes opposing viewpoints.[9][10]
There are many different ways of writing comments and many commentators who offer sometimes conflicting advice.10
Code description
Comments can be used to summarize code or to explain the programmer's intent. According to this school of thought, restating the code in plain English is considered superfluous; the need to re-explain code may be a sign that it is too complex and should be rewritten.
:"Don't document bad code – rewrite it." [11]
:"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." [12]
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.
vtx = server.mappath("local settings")
Algorithmic description
Sometimes source code contains a novel or noteworthy solution to a specific problem. In such cases, comments may contain an explanation of the methodology. Such explanations may include diagrams and formal mathematical proofs. This may constitute explanation of the code, rather than a clarification of its intent; but others tasked with maintaining the code base may find such explanation crucial. This might especially be true in the case of highly-specialized problem domains; or rarely-used optimizations, constructs or function-calls.[13]
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);
Resource inclusion
Logos, diagrams, and flowcharts consisting of ASCII art constructions can be inserted into source code formatted as a comment.[14] 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.
The following code fragment is a simple ASCII diagram depicting the process flow for a system administration script contained in a Windows Script File running under Windows Script Host. Although a section marking the code appears as a comment, the diagram itself actually appears in an XMLCDATA section, which is technically considered distinct from comments, but can serve similar purposes.[15]
_HostApp_(Main_process)
____">
V
script.wsf (app_cmd) --> ClientApp (async_run, batch_process)
|
|
V
mru.ini (mru_history)
>
Although this identical diagram could easily have been included as a comment, the example illustrates one instance where a programmer may opt not to use comments as a way of including resources in source code.15
Debugging
A common developer practice is to comment out a code snippet as a comment, such that it will not be executed in the final program. For example, one might write:
if (opt.equals ("e"))
opt_enabled = true;
/ ★ if (opt.equals ("d"))
opt_debug = true; ★ /
if (opt.equals ("v"))
opt_verbose = true;
The above code fragment suggests that the programmer opted to disable the debugging option for some reason.
Automatic documentation generation
Some programming tools read structured information in comments and automatically generate documentation. Keeping documentation within source code comments is considered as one way to simplify the documentation process, as well as increase the chances that the documentation will be kept up to date with changes in the code.[16]
Examples of documentation 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# and Visual Basic implement a similar feature called "XML Comments" which are read by IntelliSense from the compiled .NET assembly.
Metadata and annotations
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.
Comments are often employed for these and related methods because they allow the use of syntax and lexical conventions that might otherwise conflict with those of the enclosing programming language. This is another sense in which it is helpful that compilers and interpreters "ignore" comments.
Warnings
Some comments are intended as warnings to other programmers that code may not be complete or may have known limitations which should be addressed. One convention for such comments is to prefix them with XXX in order to allow ease of later identifications of potential problems.[17]
Philosophy
There are various normative and philosophical approaches regarding the proper use of comments in source code. Some of these are informal and based on personal preference, while others are published or promulgated as formal guidelines.
Necessity of comments
Some contend that comments are often not necessary or unhelpful because well-written source should be mostly self explanatory;11[18] others contend 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).[19][20]
In between these views is the philosophy that comments are neither beneficial nor harmful by themselves, and what matters is that they are correct and kept in synch with the source code, and omitted if they are superfluous, excessive, difficult to maintain or otherwise unhelpful.[21]
Level of detail
Depending on the intended audience of the code and other considerations, the level of detail and description may vary considerably.
For example, the following would be suitable in an introductory text designed to teach beginning programming:
String s := "Wikipedia"; / ★ Assigns the value "Wikipedia" to the variable s. ★ /
This level of detail, however, would not be appropriate in the context of production code, or other situations involving experienced developers. Such rudimentary descriptions are inconsistent with the guideline: "Good comments ... clarify intent."12 Additionally, for professional coding environments, the level of detail is ordinarily well-defined to meet a specific performance requirement defined by business operations.20
Offensive comments
Sometimes comments in source code are used as a way to relieve stress or to speak unfavorably about development tools, competitors, employers, or working conditions. Some commentators deem this highly inappropriate and recommend against including potentially offensive remarks in comments, especially if there is any possibility that the source code may later be viewed by anyone besides the original developer responsible for it.[22] The occurrence of this phenomenon can be easily seen from online resources that track profanity in source code.[23]
Comments in web templates
Web development presents a special security challenge related to comments, because it is not uncommon for HTML comments to be viewable in plain text by any user of the application. Sections of code that are "commented out" in HTML templates may therefore present a security vulnerability.[24]
Styles
There are many stylistic alternatives available when considering how comments should appear in source code. For larger projects involving a team of developers, comment styles are either agreed upon before a project starts, or evolve as a matter of convention or necessity as a project grows. Usually programmers prefer styles that are consistent, non-obstructive, easy to modify, and difficult to break.[25]
The following code fragments in C demonstrate just a tiny example of how comments can vary stylistically, while still conveying the same basic information: / ★
This is the comment body.
Variation One.
/// begin: Variation Three.
/// -------------------------
/// This is the comment body.
/// -------------------------
Factors such as personal preference, flexibility of programming tools, and other considerations tend to influence the stylistic variants used in source code. For example, Variation Two might be disfavored among programmers who do not have source code editors that can automate the alignment and visual appearance of text in comments.
Software consultant and technology commentator Allen Holub[26] is one expert who advocates aligning the left edges of comments:[27]
/ ★ 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).
Sometimes projects try to enforce rules like "one comment every ten lines". These kinds of rules can be counterproductive when too rigorous, but may provide a useful standard of measurement and consistency if the project participants deem it necessary.
Tags
Certain tags are used in comments to assist in indexing common issues. Such tags can be searched with common programming tools, such as the UNIXgrep utility.
★ 'FIXME' is used to mark potential problematic code that requires special attention and/or review.
★ 'NOTE' is used to document inner workings of code and indicate potential pitfalls.
★ 'TODO' is used to indicate planned enhancements.
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
This C code fragment demonstrates the use of a prologue comment or "block comment" to describe the purpose of a conditional statement. The comment explains key terms and concepts, and includes a short signature by the programmer who authored the code.
/ ★
★ 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
This excerpt is from the fork.c file from the Linux kernel source.
Classic BASIC
This BASIC code fragment is a completely functioning program in which the comments describe what the program does for the benefit of novice programmers. 10 REM This BASIC program shows the use of the PRINT and GOTO statements.
15 REM It fills the screen with the word "WIKIPEDIA"
20 PRINT "WIKIPEDIA"
30 GOTO 20
When run, this program repeatedly prints the word "WIKIPEDIA" (without quotes) in an endless loop.
Fortran 90
This Fortran code fragment demonstrates how comments are used in that language, with the comments themselves describing the basic formatting rules. ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★ ★
★ 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
This Java code fragment shows a block comment used to describe the setToolTipText method. The formatting is consistent with Sun Microsystems javadoc standards. The comment is designed to be read by the javadoc processor.
/ ★ ★
★ 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) {
Unique variants
Some developers have either implemented or begun work on providing alternate modalities for specifying comments in source code. This type of extension is possible since any type of resource can be specified in text (given the proper encoding), and because Integrated Development Environments provide increasingly flexible options for linking to related external content.
Audio comments
One example of this variability of comment types is the use of audio files to include voice annotations in source code.[28]
See also
★ Comment (computing) for a general discussion on the use of comments in computing.
★ Docstring, a specific type of comment that is parsed and retained throughout the runtime of the program
Notes and references
1. Some programming environments include comments as one element of the language syntax that is retained for further processing, instead of discarded once recognized by the language processor. 2. Comments must be indicated in a way that allows a source code processor to recognize them as such. This is often simplified by saying comments are "ignored" (after they have been recognized and discarded) by the processor. 3. Comments can be processed in various ways to generate documentation external to the source code itself. See e.g., Comparison of documentation generators. 4. 5. Computer Fundamentals and Programming in C, , J.B., Dixit, Laxmi Publications, 2003, ISBN 8170088828 6. MATLAB Guide, , Desmond, Higham, SIAM, 2005, ISBN 0898715784 7. The Elements of Java Style, , Al, Vermeulen, Cambridge University Press, 2000, ISBN 0521777682 8.Using the right comment in Java 9. Applied Pattern Recognition: Algorithms and Implementation in C++, , Dietrich, W. R., Springer, 2003, 3528355581 offers viewpoints on proper use of comments in source code. p. 66. 10. Software Engineering Handbook, , Jessica, Keyes, CRC Press, 2003, 0849314798 discusses comments and the "Science of Documentation" p. 256. 11. ''The Elements of Programming Style'', Kernighan & Plauger 12. ''Code Complete'', McConnell 13. Code reading: The Open Source Perspective, , Diomidis, Spinellis, Addison-Wesley, 2003, ISBN 0201799405 14.CodePlotter 1.6 - Add and edit diagrams in your code with this 'Visio-like' tool 15. Web Design in a Nutshell: A Desktop Quick Reference, , Jennifer, Niederst, O'Reilly, 2006, ISBN 0596009879 Sometimes the difference between a "comment" and other syntax elements of a programming or markup language entails subtle nuances. Niederst indicates one such situation by stating: "Unfortunately, XML software thinks of comments as unimportant information and may simply remove the comments from a document before processing it. To avoid this problem, use an XML CDATA section instead." 16. The Object Primer: Agile Model-Driven Development with UML 2.0, , Scott, Ambler, Cambridge University Press, 2004, ISBN 1397805218 17./ ★ You Are Expected to Understand This ★ / (editorial) Arensburger, Andrew 18.Worst Practice - Bad Comments 19. Java, Java, Java: object-oriented problem solving, , Ralph, Morelli, Prentice Hall College, 2006, ISBN 0131474340 20.How to Write Doc Comments for the Javadoc Tool JavaDoc guidelines specify that comments are crucial to the platform. Additionally, the appropriate level of detail is fairly well-defined: "We spend time and effort focused on specifying boundary conditions, argument ranges and corner cases rather than defining common programming terms, writing conceptual overviews, and including examples for developers." 21. C++ Gotchas: Avoiding Common Problems in Coding and Design, , Stephen C, Dewhurst, Addison-Wesley Professional, 2002, ISBN 0321125185 22. Practical Development Environments, , Matthew B., Doar, O'Reilly, 2005, ISBN 0596007965 23. (see e.g., http://www.vidarholen.net/contents/wordcount/ Linux Swear Count, http://www.google.com/codesearch?hl=en&lr=&q=fucking Google Code Search). 24. Surviving Security: How to Integrate People, Process, and Technology, , Mandy, Andress, CRC Press, 2003, ISBN 0849320429 25.Coding Style 26.Allen Holub 27. Allen Holub, ''Enough Rope to Shoot Yourself in the Foot'', ISBN 0-07-029689-8, 1995, McGraw-Hill 28. http://dev.devbiz.com/blogs/hakan/archive/2005/08/03/voice_comments.aspx Voice Comments