Jump to content

Comment (computer programming)

From Wikipedia, the free encyclopedia
(Redirected from Commenting code)
An illustration of Java source code with prologue comments indicated in red and inline comments in green. Program code is in blue.

In computer programming, a comment is text embedded in source code that a translator (compiler or interpreter) ignores. Generally, a comment is an annotation intended to make the code easier for a programmer to understand – often explaining an aspect that is not readily apparent in the symbolic (non-comment) code.[1][2]

Comments can be processed by some development tools to provide capabilites such as API document generation, static analysis, and version control integration.

The syntax of comments varies considerably by programming language. But generally, the flexibility supported by comments allows for a wide degree of style variability. To promote uniformity, conventions for their style are commonly part of a programming style guide. But, best practices are disputed and contradictory.[3][4]

Common attributes

[edit]

Support for code comments is defined by each programming language. The features differ by language, but there are several common attributes that apply throughout.

Most languages support formatting comments either as a block (also called prologue or stream) or a line (also called inline).[5]

A block comment is delimited with special text that marks the start and end of the block. It can span multiple lines or occupy any part of a line. Some languages (such as MATLAB) allow block comments to be recursively nested inside one another, but others (such as Java) do not.[6][7][8]

In modern languages, a line comment starts with a delimiter and continues until the end of the line. Some older languages designated a column at which subsequent text is considered comment text.[8]

Most modern languages support both block and line comments – using different delimiters for each. For example, C, C++ and their many variants support block comments delimited by /* and */ and line comments delimited by //. Other languages support only one type of comment.[8]

Examples of use

[edit]

Describe intent

[edit]

Comments can explain the author's intent. Some contend that describing what the code does is superfluous; the need to explain what it does is a sign that it is too complex and should be re-worked.

"Don't document bad code – rewrite it."[9]
"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."[10]

Highlight unusual practice

[edit]

Comments may explain why a choice was made to write code that is counter to convention or best practice. 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")

The example below explains why an insertion sort was chosen instead of a quicksort, as the former is, in theory, slower than the latter.

 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);

Algorithmic description

[edit]

Comments can describe an algorithm as pseudocode. This could be done before writing the code as a first draft. If left in the code, it can simplify code review by allowing comparison of the resulting code with the intended logic. For example:

/* loop backwards through all elements returned by the server 
(they should be processed chronologically)*/
for (i = (numElementsReturned - 0); i >= 1; i--) {
    /* process each element's data */
    updatePattern(i, returnedElements[i]);
}

Sometimes code contains a novel or noteworthy solution that warrants an explanatory comment. Such explanations might be lengthy and include diagrams and formal mathematical proofs. This may describe what the code does rather than intent, but may be useful for maintaining the code. This might apply for highly specialized problem domains or rarely used optimizations, constructs or function-calls.[11]

Resource inclusion

[edit]

Logos, diagrams, and flowcharts consisting of ASCII art constructions can be inserted into source code formatted as a comment.[12] Further, 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 XML CDATA section, which is technically considered distinct from comments, but can serve similar purposes.[13]

<!-- begin: wsf_resource_nodes -->
<resource id="ProcessDiagram000">
<![CDATA[
 HostApp (Main_process)
    |
    V
script.wsf (app_cmd) --> ClientApp (async_run, batch_process)
                |
                |
                V
         mru.ini (mru_history)  
]]>
</resource>

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.[13]

Metadata

[edit]

Comments are used for store metadata. Sometimes, a software maintainer puts submission guidelines in comments to help people send improvements to the maintainer. Other common metadata includes the name of the original author and subsequent maintainers, dates when first written and modified, link to development and user documentation, software license information.

Some programming tools write metadata into the code as comments.[14] This may include insert positions for automatic header file inclusion, commands to set the file's syntax highlighting mode,[15] or the file's revision number.[16]

Reference

[edit]

When some aspect of the code is based on information in an external reference, comments link to the reference. For example as a URL or book name and page number.

Comment out

[edit]

A common developer practice is to comment out one or more lines of code. The programmer adds comment syntax that converts code into comments so that what was executable code will no longer be executed at runtime. Sometimes this technique is used to find the cause of a bug. By systematically commenting out and running parts of the program, the offending source code can be located.

Many IDEs support adding and removing comments with convenient user interface such as a keyboard shortcut.

Documentation generation

[edit]

A documentation generator can parse information from a codebase to generate API documentation. Many support reading information from comments to control the content and formatting of the resulting document. Some claim that storing documentation information in code comments simplifies the documenting process, as well as increase the chances that the documentation will be kept up to date.[17] Examples include Javadoc, Ddoc, Doxygen, Visual Expert and PHPDoc. Forms of docstring are supported by Python, Lisp, Elixir, and Clojure.[18] C#, F# and Visual Basic .NET implement a similar feature called "XML Comments" which are read by IntelliSense from the compiled .NET assembly.[19]

Syntax extension

[edit]

Occasionally syntax elements that were originally intended to be comments are re-purposed to convey additional information to a program, such as "conditional comments". Such "hot comments" may be the only practical solution that maintains backward-compatibility, but are widely regarded as a kludge.[20]

One specific example are docblocks, which are specially-formatted comments used to document a specific segment of code. This makes the DocBlock format independent of the target language (as long as it supports comments); however, it may also lead to multiple or inconsistent standards.

Directives

[edit]

There are cases where the normal comment characters are co-opted to create a special directive for an editor or interpreter.

Two examples of this directing an interpreter are:

  • The Unix "shebang" – #! – used on the first line of a script to point to the interpreter to be used.
  • "Magic comments" identifying the encoding a source file is using,[21] e.g. Python's PEP 263.[22]

The script below for a Unix-like system shows both of these uses:

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
print("Testing")

Somewhat similar is the use of comments in C to communicate to a compiler that a default "fallthrough" in a case statement has been done deliberately:

switch (command) {
    case CMD_SHOW_HELP_AND_EXIT:
      do_show_help();
      /* Fall thru */
    case CMD_EXIT:
      do_exit();
      break;
    case CMD_OTHER:
      do_other();
      break;
    /* ... etc. ... */
  }

Inserting such a /* Fall thru */ comment for human readers was already a common convention, but in 2017 the gcc compiler began looking for these (or other indications of deliberate intent), and, if not found, emitting: "warning: this statement may fall through".[23]

Many editors and IDEs will read specially formatted comments. For example, the "modeline" feature of Vim; which would change its handling of tabs while editing a source with this comment included near the top of the file:

# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4

Stress relief

[edit]

Sometimes programmers will add comments as a way to relieve stress by commenting about development tools, competitors, employers, working conditions, or the quality of the code itself.[24] The occurrence of this phenomenon can be easily seen from online resources that track profanity in source code.[25]

Normative views

[edit]

There are various normative views and long-standing opinions regarding the proper use of comments in source code.[26][27] Some of these are informal and based on personal preference, while others are published or promulgated as formal guidelines for a particular community.[28]

Need for comments

[edit]

Experts have varying viewpoints on whether, and when, comments are appropriate in source code.[9][29] Some assert that source code should be written with few comments, on the basis that the source code should be self-explanatory or self-documenting.[9] Others suggest 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).[30][31]

In between these views is the assertion that comments are neither beneficial nor harmful by themselves, and what matters is that they are correct and kept in sync with the source code, and omitted if they are superfluous, excessive, difficult to maintain or otherwise unhelpful.[32][33]

Comments are sometimes used to document contracts in the design by contract approach to programming.

Level of detail

[edit]

Depending on the intended audience of the code and other considerations, the level of detail and description may vary considerably.

For example, the following Java comment 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."[10] Further, for professional coding environments, the level of detail is ordinarily well defined to meet a specific performance requirement defined by business operations.[31]

Styles

[edit]

As free-form text, comments can be styled in a wide variety of ways. Many prefer a style that is consistent, non-obstructive, easy to modify, and difficult to break. As some claim that a level of consistency is valuable and worthwhile, a consistent commenting style is sometimes agreed upon before a project starts or emerges as development progresses.[34]

The following C fragments show some of diversity in block comment style:

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

Factors such as personal preference, flexibility of programming tools can influence the commenting style used. For example, the first might be preferred by programmers who use a source code editor that does not automatically format a comment as shown in the second example.

Software consultant and technology commentator Allen Holub[35] advocates aligning the left edges of comments:[36]

 /* 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.
 */

In many languages, a line comment can follow symbolic code such that the comment is inline and generally describes the code to the left of it. For example, in this Perl:

print $s . "\n";     # Add a newline character after printing

If a language supports both line and block comments, programming teams may decide upon a convention of when to use which. For example, line comments only for minor comments, and block comments to for higher-level abstractions.

Tags

[edit]

Programmers often use one of select words – also konwn as tags, codetags[37][38] and tokens[39] – to categorize the information in a comment. Programmers may leverage these tags by searching for them via a text editor or grep. Some editors highlight comment text based on tags.

Commonly used tags include:

  • BUG, DEBUG — identifies a known bug; maybe implying it should be fixed
  • FIXME — implies that there is work to do to fix a bug
  • HACK, BODGE, KLUDGE — marks a solution that might be considered low quality
  • TODO — describes some work to do
  • NOTE — relatively general information
  • UNDONE — a reversal or "roll back" of previous code

Examples

[edit]

Comparison

[edit]

Typographic conventions to specify comments vary widely. Further, individual programming languages sometimes provide unique variants.

Ada

[edit]

Ada supports line comments delimited with '--'. It does not support block comments. For example:

  -- the air traffic controller task takes requests for takeoff and landing
   task type Controller (My_Runway: Runway_Access) is
      -- task entries for synchronous message passing
      entry Request_Takeoff (ID: in Airplane_ID; Takeoff: out Runway_Access);
      entry Request_Approach(ID: in Airplane_ID; Approach: out Runway_Access);
   end Controller;

APL

[edit]

APL uses for a line comment. For example:

⍝ Now add the numbers:
ca+b ⍝ addition

In dialects that have the ("left") and ("right") primitives, comments can often be inside or separate statements, in the form of ignored strings:

d2×c 'where' ca+ 'bound' b

AppleScript

[edit]

AppleScript supports both line and block comments. For example:

(*
This program displays a greeting.
*)
on greet(myGreeting)
     display dialog myGreeting & " world!"
end greet

-- Show the greeting
greet("Hello")

BASIC

[edit]

Early versions of BASIC used REM (short for remark) for a line comment.

10 REM This BASIC program shows the use of the PRINT and GOTO Statements.
15 REM It fills the screen with the phrase "HELLO"
20 PRINT "HELLO"
30 GOTO 20

In later variations, including Quick Basic, Q Basic, Visual Basic, Visual Basic .NET, VB Script, FreeBASIC and Gambas a line comment is delimted with apostrophe ('). An example in Visual Basic .NET:

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ' The following code is executed when the user
        ' clicks the button in the program's window.
        rem comments still exist.

        MessageBox.Show("Hello, World") 'Show a pop-up window with a greeting
    End Sub
End Class

C

[edit]

In C, C++ and many related languages, the line comment delimiter is // and a block is delimited by /* and */. Originally, C lacked the line comment, but it was added in C99. For example:

 /*
  * 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;

Cisco IOS and IOS-XE configuration

[edit]

The exclamation point (!) may be used to mark comments in a Cisco router's configuration mode, however such comments are not saved to non-volatile memory (which contains the startup-config), nor are they displayed by the "show run" command.[40][41]

It is possible to insert human-readable content that is actually part of the configuration, and may be saved to the NVRAM startup-config via:

  • The "description" command, used to add a description to the configuration of an interface or of a BGP neighbor
  • The "name" parameter, to add a remark to a static route
  • The "remark" command in access lists
! Paste the text below to reroute traffic manually
config t
int gi0/2
no shut
ip route 0.0.0.0 0.0.0.0 gi0/2 name ISP2
no ip route 0.0.0.0 0.0.0.0 gi0/1 name ISP1
int gi0/1
shut
exit

ColdFusion

[edit]

ColdFusion uses comments similar to HTML comments, but instead of two dashes, it uses three. These comments are caught by the ColdFusion engine and not printed to the browser.

Such comments are nestable.

 <!--- This prints "Hello World" to the browser.
   <!--- This is a comment used inside the first one.
   --->
 --->
 <cfoutput>
   Hello World<br />
 </cfoutput>

D

[edit]

D uses C++-style comments, as well as nestable D-style multiline comments, which start with '/+' and end with '+/'.

// This is a single-line comment.
/* This is a multiline comment.

*/
/+ This is a
  /+ nested +/
    comment +/

Fortran IV

[edit]

This Fortran IV code fragment demonstrates how comments are used in that language, which is very column-oriented. A letter "C" in column 1 causes the entire line to be treated as a comment.

C
C Lines that begin with 'C' (in the first or 'comment' column) are comments
C
      WRITE (6,610)
  610 FORMAT(12H HELLO WORLD)
      END

Note that the columns of a line are otherwise treated as four fields: 1 to 5 is the label field, 6 causes the line to be taken as a continuation of the previous statement; and declarations and statements go in 7 to 72.

Fortran 90

[edit]

This Fortran code fragment demonstrates how comments are used in that language, with the comments themselves describing the basic formatting rules.

!* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
!* All characters after an exclamation mark are considered as comments *
!* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
program comment_test
    print '(A)', 'Hello world' ! Fortran 90 introduced the option for inline comments.
end program

Haskell

[edit]

Line comments in Haskell start with '--' (two hyphens) until the end of line, and multiple line comments start with '{-' and end with '-}'.

{- this is a comment
on more lines -}
-- and this is a comment on one line
putStrLn "Wikipedia"  -- this is another comment

Haskell also provides a literate programming method of commenting known as "Bird Style".[42] In this all lines starting with > are interpreted as code, everything else is considered a comment. One additional requirement is that you always leave a blank line before and after the code block:

In Bird-style you have to leave a blank before the code.

> fact :: Integer -> Integer
> fact 0 = 1
> fact (n+1) = (n+1) * fact n

And you have to leave a blank line after the code as well.

Literate programming can also be done in Haskell, using LaTeX. The code environment can be used instead of the Richard Bird's style: In LaTeX style this is equivalent to the above example, the code environment could be defined in the LaTeX preamble. Here is a simple definition:

\usepackage{verbatim}
\newenvironment{code}{\verbatim}{\endverbatim}

later in

% the LaTeX source file
The \verb|fact n| function call computes $n!$ if $n\ge 0$, here is a definition:\\
\begin{code}
fact :: Integer -> Integer
fact 0 = 1
fact (n+1) = (n+1) * fact n
\end{code}
Here more explanation using \LaTeX{} markup

Java

[edit]

This Java code fragment shows both block and line comments. The block comment is designed to be processed by Javadoc.

/**
 * This is a block comment in Java.
 * The setToolTipText method registers the text to display in a tool tip.
 * The text is displayed when the cursor lingers over the component.
 *
 * @param text  The string to be displayed.  If 'text' is null,
 *              the tool tip is turned off for this component.
 */
public void setToolTipText(String text) {
    // This is an inline comment in Java. TODO: Write code for this method.
}

JavaScript

[edit]

JavaScript uses // to precede comments and /* */ for multi-line comments.

// A single line JavaScript comment
var iNum = 100;
var iTwo = 2; // A comment at the end of line
/*
multi-line
JavaScript comment
*/

Lua

[edit]

Lua uses double-hyphens, --, for single line comments in a similar way to Ada, Eiffel, Haskell, SQL and VHDL languages. Lua also has block comments, which start with --[[ and run until a closing ]] For example:

--[[A multi-line
long comment
]]
print(20)   -- print the result

A common technique to comment out a segment of code,[43] is to enclose the code between --[[ and --]], as below:

--[[
print(10)
--]]
-- no action (commented out)

In this case, it's possible to enable the code for use (uncomment-out) by adding a single hyphen to the first line:

---[[
print(10)
--]]
--> 10

The --[[ in the first line starts a long comment, and the two hyphens in the last line are still inside that comment. In the second example, the sequence ---[[ starts an ordinary, single-line comment, so that the first and the last lines become independent comments. In this case, the print is outside comments. In this case, the last line becomes an independent comment, as it starts with --.

MATLAB

[edit]

In MATLAB's programming language, the '%' character indicates a single-line comment. Multi line comments are also available via %{ and %} brackets and can be nested, e.g.

% These are the derivatives for each term
d = [0 -1 0];

%{
  %{
    (Example of a nested comment, indentation is for cosmetics (and ignored).)
  %}
  We form the sequence, following the Taylor formula.
  Note that we're operating on a vector.
%}
seq = d .* (x - c).^n ./(factorial(n))

% We add-up to get the Taylor approximation
approx = sum(seq)

Nim

[edit]

Nim uses the '#' character for inline comments. Multi-line block comments are opened with '#[' and closed with ']#'. Multi-line block comments can be nested.

Nim also has documentation comments that use mixed Markdown and ReStructuredText markups. The inline documentation comments use '##' and multi-line block documentation comments are opened with '##[' and closed with ']##'. The compiler can generate HTML, LaTeX and JSON documentation from the documentation comments. Documentation comments are part of the abstract syntax tree and can be extracted using macros.[44]

## Documentation of the module *ReSTructuredText* and **MarkDown**
# This is a comment, but it is not a documentation comment.

type Kitten = object  ## Documentation of type
  age: int  ## Documentation of field

proc purr(self: Kitten) =
  ## Documentation of function
  echo "Purr Purr"  # This is a comment, but it is not a documentation comment.

# This is a comment, but it is not a documentation comment.

OCaml

[edit]

OCaml supports nestable comments. For exmaple:

codeLine(* comment level 1(*comment level 2*)*)

Pascal, Delphi

[edit]

In Pascal and Delphi, comments are delimited by '{ ... }'. Comment lines can also start with '\\' . As an alternative, for computers that do not support these characters, '(* ... *)' are allowed.[45] In Niklaus Wirth's more modern family of languages (including Modula-2 and Oberon), comments are delimited by '(* ... *)'.[46][47] Comments can be nested. // can be included in a {} and {} can be included in a (**). For example:

(* test diagonals *)
columnDifference := testColumn - column;
if (row + columnDifference = testRow) or
    .......

Perl

[edit]

Line comments in Perl, and many other scripting languages, begin with a hash (#) symbol.

# A simple example
# 
my $s = "Wikipedia"; # Sets the variable s to "Wikipedia".
print $s . "\n";     # Add a newline character after printing

Instead of a regular block commenting construct, Perl uses Plain Old Documentation, a markup language for literate programming,[48] for instance:[49]

=item Pod::List-E<gt>new()

Create a new list object. Properties may be specified through a hash
reference like this:

  my $list = Pod::List->new({ -start => $., -indent => 4 });

See the individual methods/properties for details.

=cut

sub new {
    my $this = shift;
    my $class = ref($this) || $this;
    my %params = @_;
    my $self = {%params};
    bless $self, $class;
    $self->initialize();
    return $self;
}

R

[edit]

R only supports inline comments started by the hash (#) character.

# This is a comment
print("This is not a comment")  # This is another comment

Raku

[edit]

Raku (previously called Perl 6) uses the same line comments and POD Documentation comments as regular Perl (see Perl section above), but adds a configurable block comment type: "multi-line / embedded comments".[50]

These start with a hash character, followed by a backtick, and then some opening bracketing character, and end with the matching closing bracketing character.[50] The content can not only span multiple lines, but can also be embedded inline.

#`{{ "commenting out" this version 
toggle-case(Str:D $s)

Toggles the case of each character in a string:

  my Str $toggled-string = toggle-case("mY NAME IS mICHAEL!");

}}

sub toggle-case(Str:D $s) #`( this version of parens is used now ){
    ...
}

PHP

[edit]

Comments in PHP can be either in C++ style (both inline and block), or use hashes. PHPDoc is a style adapted from Javadoc and is a common standard for documenting PHP code.

Starting in PHP 8, the # sign can only mean a comment if it's not immediately followed by '['. Otherwise, it will mean a function attribute, which runs until ']':

/**
 * This class contains a sample documentation.
 * 
 * @author Unknown
 */
#[Attribute]
class MyAttribute {
    const VALUE = 'value';
    // This is an inline comment. It starts with '//', like in C++.
    private $value;
    # This is a Unix-style inline comment, which starts with '#'.
    public function __construct($value = null) {
        $this->value = $value;
    }
    /*
    This is a multiline comment.

    These comments cannot be nested.
    */

}

PowerShell

[edit]

Comments in Windows PowerShell

# Single line comment
Write-Host "Hello, World!"

<# Multi
   Line
   Comment #>

Write-Host "Goodbye, world!"

Python

[edit]

Line comments in Python are delimiated by the hash (#) character. For example:

# This program prints "Hello World" to the screen
print("Hello World!")  # Note the new syntax

Python does not provide for block comments[51] but a bare string literal represented by a triple-quoted string can be and often is used for this purpose.[52][51] In the examples below, the triple double-quoted strings act like comments, but are also treated as docstrings:

"""
Assuming this is file mymodule.py, then this string, being the
first statement in the file, will become the "mymodule" module's
docstring when the file is imported.
"""

class MyClass:
    """The class's docstring"""

    def my_method(self):
        """The method's docstring"""

def my_function():
    """The function's docstring"""

Ruby

[edit]

Inline comments in Ruby start with the # character.

To create a multiline comment, one must place "=begin" at the start of a line, and then everything until "=end" that starts a line is ignored. Including a space after the equals sign in this case throws a syntax error.

puts "This is not a comment"

# this is a comment

puts "This is not a comment"

=begin

whatever goes in these lines

is just for the human reader

=end

puts "This is not a comment"

SQL

[edit]

Standard comments in SQL are in single-line-only form, using two dashes:

-- This is a single line comment
-- followed by a second line
SELECT COUNT(*)
       FROM Authors
       WHERE Authors.name = 'Smith'; -- Note: we only want 'smith'
                                     -- this comment appears after SQL code

Alternatively, a comment format syntax identical to the "block comment" style used in the syntax for C and Java is supported by Transact-SQL, MySQL, SQLite, PostgreSQL, and Oracle.[53][54][55][56][57]

MySQL also supports comments from the hash (#) character to the end of the line.

Swift

[edit]

In Swift, line comments begin //. Block comments are delimited by /*(/*) and */. For example:

// This is a comment.
/* This is also a comment
 but is written over multiple lines. */

Block comments can be nested. For example:

/* This is the start of the outer comment.
    /* This is the nested comment. */
This is the end of the outer comment. */

XML and HTML

[edit]

A block comment in XML and HTML is delimited by <!-- and -->. Line comment is not supported. For example,

<!-- select the context here -->
<param name="context" value="public" />

For compatibility with SGML, double-hyphen (--) is not allowed inside comments.

Security issues

[edit]

In interpreted languages the comments are viewable to the end user of the program. In some cases, such as sections of code that are "commented out", this may present a security vulnerability.[58]

See also

[edit]

Notes and references

[edit]
  1. ^ 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).Penny Grubb, Armstrong Takang (2003). Software Maintenance: Concepts and Practice. World Scientific. pp. 7, plese start120–121. ISBN 978-981-238-426-3.
  2. ^ For purposes of this article, programming language comments are treated as indistinct from comments that appear in markup languages, configuration files and other similar contexts. Moreover, markup language is often closely integrated with programming language code, especially in the context of code generation. See e.g., Ganguli, Madhushree (2002). Making Use of Jsp. New York: Wiley. ISBN 978-0-471-21974-3., Hewitt, Eben (2003). Java for Coldfusion Developers. Upper Saddle River: Pearson Education. ISBN 978-0-13-046180-3.
  3. ^ W. R., Dietrich (2003). Applied Pattern Recognition: Algorithms and Implementation in C++. Springer. ISBN 978-3-528-35558-6. offers viewpoints on proper use of comments in source code. p. 66.
  4. ^ Keyes, Jessica (2003). Software Engineering Handbook. CRC Press. ISBN 978-0-8493-1479-7. discusses comments and the "Science of Documentation" p. 256.
  5. ^ Dixit, J.B. (2003). Computer Fundamentals and Programming in C. Laxmi Publications. ISBN 978-81-7008-882-0.
  6. ^ Higham, Desmond (2005). MATLAB Guide. SIAM. ISBN 978-0-89871-578-1.
  7. ^ Vermeulen, Al (2000). The Elements of Java Style. Cambridge University Press. ISBN 978-0-521-77768-1.
  8. ^ a b c "Using the right comment in Java". 2000-03-04. Retrieved 2007-07-24.
  9. ^ a b c The Elements of Programming Style, Kernighan & Plauger
  10. ^ a b Code Complete, McConnell
  11. ^ Spinellis, Diomidis (2003). Code reading: The Open Source Perspective. Addison-Wesley. ISBN 978-0-201-79940-8.
  12. ^ "CodePlotter 1.6 – Add and edit diagrams in your code with this 'Visio-like' tool". Archived from the original on 2007-07-14. Retrieved 2007-07-24.
  13. ^ a b Niederst, Jennifer (2006). Web Design in a Nutshell: A Desktop Quick Reference. O'Reilly. ISBN 978-0-596-00987-8.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."
  14. ^ See e.g., Wynne-Powell, Rod (2008). Mac OS X for Photographers: Optimized Image Workflow for the Mac User. Oxford: Focal Press. p. 243. ISBN 978-0-240-52027-8.
  15. ^ Lamb, Linda (1998). Learning the VI Editor. Sebastopol: O'Reilly & Associates. ISBN 978-1-56592-426-0. describes the use of modeline syntax in Vim configuration files.
  16. ^ See e.g., Berlin, Daniel (2006). Practical Subversion, Second Edition. Berkeley: APress. p. 168. ISBN 978-1-59059-753-8.
  17. ^ Ambler, Scott (2004). The Object Primer: Agile Model-Driven Development with UML 2.0. Cambridge University Press. ISBN 978-1-397-80521-8.
  18. ^ Function definition with docstring in Clojure
  19. ^ Murach. C# 2005. p. 56.
  20. ^ c2: HotComments
  21. ^ "class Encoding". Ruby. ruby-lang.org. Retrieved 5 December 2018.
  22. ^ "PEP 263 – Defining Python Source Code Encodings". Python.org. Retrieved 5 December 2018.
  23. ^ Polacek, Marek (2017-03-10). "-Wimplicit-fallthrough in GCC 7". Red Hat Developer. Red Hat. Retrieved 10 February 2019.
  24. ^ Lisa Eadicicco (27 March 2014). "Microsoft Programmers Hid A Bunch Of Profanity In Early Software Code". Business Insider Australia. Archived from the original on 29 December 2016.
  25. ^ (see e.g., Linux Swear Count).
  26. ^ Goodliffe, Pete (2006). Code Craft. San Francisco: No Starch Press. ISBN 978-1-59327-119-0.
  27. ^ Smith, T. (1991). Intermediate Programming Principles and Techniques Using Pascal. Belmont: West Pub. Co. ISBN 978-0-314-66314-6.
  28. ^ See e.g., Koletzke, Peter (2000). Oracle Developer Advanced Forms & Reports. Berkeley: Osborne/McGraw-Hill. ISBN 978-0-07-212048-6. page 65.
  29. ^ "Worst Practice - Bad Comments". Retrieved 2007-07-24.
  30. ^ Morelli, Ralph (2006). Java, Java, Java: object-oriented problem solving. Prentice Hall College. ISBN 978-0-13-147434-5.
  31. ^ a b "How to Write Doc Comments for the Javadoc Tool". Retrieved 2007-07-24. Javadoc guidelines specify that comments are crucial to the platform. Further, 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."
  32. ^ Yourdon, Edward (2007). Techniques of Program Structure and Design. University of Michigan. 013901702X.Non-existent comments can make it difficult to comprehend code, but comments may be detrimental if they are obsolete, redundant, incorrect or otherwise make it more difficult to comprehend the intended purpose for the source code.
  33. ^ Dewhurst, Stephen C (2002). C++ Gotchas: Avoiding Common Problems in Coding and Design. Addison-Wesley Professional. ISBN 978-0-321-12518-7.
  34. ^ "Coding Style". Archived from the original on 2007-08-08. Retrieved 2007-07-24.
  35. ^ "Allen Holub". Archived from the original on 2007-07-20. Retrieved 2007-07-24.
  36. ^ Allen Holub, Enough Rope to Shoot Yourself in the Foot, ISBN 0-07-029689-8, 1995, McGraw-Hill
  37. ^ "PEP 0350 – Codetags", Python Software Foundation
  38. ^ "Never Forget Anything Before, After and While Coding", Using "codetag" comments as productive remainders
  39. ^ "Using the Task List", msdn.microsoft.com
  40. ^ "Leave a comment in running-config". Cisco Learning Network (discussion forum).
  41. ^ "Managing Configuration Files Configuration Guide, Cisco IOS XE Release 3S (ASR 900 Series)".
  42. ^ "Literate programming". haskell.org.
  43. ^ "Programming in Lua 1.3". www.Lua.org. Retrieved 2017-11-08.
  44. ^ macros.extractDocCommentsAndRunnables
  45. ^ Kathleen Jensen, Niklaus Wirth (1985). Pascal User Manual and Report. Springer-Verlag. ISBN 0-387-96048-1.
  46. ^ Niklaus Wirth (1983). Programming in Modula-2. Springer-Verlag. ISBN 0-387-15078-1.
  47. ^ *Martin Reiser, Niklaus Wirth (1992). Programming in Oberon. Addison-Wesley. ISBN 0-201-56543-9.
  48. ^ "perlpod – the Plain Old Documentation format". Retrieved 2011-09-12.
  49. ^ "Pod::ParseUtils – helpers for POD parsing and conversion". Retrieved 2011-09-12.
  50. ^ a b "Perl 6 Documentation – Syntax (Comments)". Retrieved 2017-04-06.
  51. ^ a b "Python 3 Basic Syntax". Archived from the original on 19 August 2021. Retrieved 25 February 2019. Triple quotes are treated as regular strings with the exception that they can span multiple lines. By regular strings I mean that if they are not assigned to a variable they will be immediately garbage collected as soon as that code executes. hence are not ignored by the interpreter in the same way that #a comment is.
  52. ^ "Python tip: You can use multi-line strings as multi-line comments", 11 September 2011, Guido van Rossum
  53. ^ Talmage, Ronald R. (1999). Microsoft SQL Server 7. Prima Publishing. ISBN 978-0-7615-1389-6.
  54. ^ "MySQL 8.0 Reference Manual". Oracle Corporation. Retrieved January 2, 2020.
  55. ^ "SQL As Understood By SQLite". SQLite Consortium. Retrieved January 2, 2020.
  56. ^ "PostgreSQL 10.11 Documentation". The PostgreSQL Global Development Group. Retrieved January 2, 2020.
  57. ^ "Oracle® Database SQL Reference". Oracle Corporation. Retrieved January 2, 2020.
  58. ^ Andress, Mandy (2003). Surviving Security: How to Integrate People, Process, and Technology. CRC Press. ISBN 978-0-8493-2042-2.

Further reading

[edit]
[edit]