Commenting

Commenting involves placing Human Readable Descriptions inside of computer programs detailing what the Code is doing. Proper use of commenting can make code maintenance much easier, as well as helping make finding bugs faster. Further, commenting is very important when writing functions that other people will use. Remember, well documented code is as important as correctly working code.

Commenting

All programs should be commented in such a manner as to easily describe (in English) the purpose of the code and any algorithms used to accomplish the purpose. A user should be able to utilize a previously written program (or function) without ever having to look at the code, simply by reading the comments.

Commenting is the "art" of describing what your program is going to do in "high level" English statements. Commenting is best done before actually writing the code for your program.

Comments are specially marked lines of text in the program that are not evaluated. There are usually two syntactic ways to comment. The first is called a single line comment and, as implied, only applies to a single line in the "source code" (the program). The second is called a Block comment and refers usually refers to a paragraph of text. A block comment has a start symbol and an end symbol and everything between is ignored by the computer.


Summary of comment types:

Here are the syntaxes of comments for variable languages. In many comments below we use the Matlab style, but you should "mentally" replace this with the appropriate style to your language.

  1. C++,Java,Action script:

    use // for a single line. Everything from the // to the end of that line of the file is ignored by the program and is only for use by the human reader of the code.

    use /* for multiple lines */

  2. Matlab:

    use % for a single line. Everything from the % to the end of that line of the file is ignored by the program and is only for use by the human reader of the code.

    use %{ comment %} for Multiline comments (or repeat the % down the left side of your paragraph).


Brief Syntactical notes on how to comment

Matlab

The comment character in Matlab is '%'. Everything from the % to the end of that line of the program is considered a comment.

As Matlab only has single line comments, to mark an entire region as a comment (called a block comment) use the single line comment over and over again.

            
          %
          % Jims Matlab code
          %
          % This is a block comment
          %
          % This code does nothing.  
          %

          % OR

          %{ one multiline  %}

          some code

          %{ 

             Jims Matlab code
          
             This is a block comment
           
             This code does nothing.  
        
             nothing = 0; % not very useful inline comment
          %}

          some code


            
          

C,C++,ActionScript, and Java

The single line comment is //. Everything from the // to the end of the line is a comment.

To mark an entire region as a comment, use /* to start the comment and */ to end the comment.

            
          /**
           * Jims C code
           *
           * This is a block comment.
           * 
           * This code does nothing.
           */
        
          int nothing = 0; // not a very useful inline comment
            
          

Where to Comment:

Comments should occur in the following places:

  1. The top of any program file.

    This is called the "Header Comment". It should include all the defining information about who wrote the code, and why, and when, and what it should do. (See Header Comment below)

  2. Above every function.

    This is called the function header and provides information about the purpose of this "sub-component" of the program.

    When and if there is only one function in a file, the function header and file header comments should be merged into a single comment. (See Function Header below)

  3. In line

    Any "tricky" code where it is not immediately obvious what you are trying to accomplish, should have comments right above it or on the same line with it.


How not to comment:

Comments should be useful high level descriptions of what the program is doing. They should not restate something that is "obvious". By using appropriate variable names, much of a program can be (almost) as easy to read as English.

Poor Matlab In-line Commenting

            
        grade(1) = 5; % this sets the first grade in the
                      % array to the value five

        % this calculate the class average and stores it in class_average
        class_average = (grade(1) + grade(2) + ... + grade(5) ) / student_count; 

        jims_age = 31; % this sets jim's age to 31
            
          

Poor C In-line Commenting

            
              int x = 5; // this sets x to 5
              int y = 2 * x; // here we double the value of x and save it in the variable y
              int average = (x + y) /2; // compute the average by dividing the sum by the number of values....
            
          

How to comment Code:

Primarily, a single "block" comment should be placed at the top of the function (or file) and describe the purpose the code and any algorithms used to accomplish the goal. In-line comments should be used sparingly, only where the code is not "self-documenting".

When you do use "in-line" comments, you should place them before (or next to) any code that is not self explanatory. This comment should detail the "idea" behind the code and what is to be accomplished. It may also say how this is to be accomplished if the "algorithm" is complex.

Example of In Line Comments

In line comments are those that are found in the general body of the program. They are usually very short (a line or two) comments making a "note" about what is going on.

In line comments are usually made using the "single line" commenting syntax of the language.

You should add "in-line" comments wherever you think a little bit of English explanation would be useful to either yourself or someone else (like a TA) who is going to read your code. Such in-line comments should be used whenever the code is not "transparent" (easy to follow simply from the names of the variables).

Matlab

            
  %
  % The header for the function would go here, but see below
  % for examples of full header comments.
  %
  % The purpose below is to show inline comments, note how the
  % fact that we only return the "positive" answer is highlighted.
  %
  function result = solve_quadratic_equation(A, B, C)
   {
      result = (-B + sqrt(B*B - 4*A*C)) / (2*A); % NOTE: we only return the positive value
   }
            
          

AS3

            
  /**
   * The header for the function would go here, but see below
   * for examples of full header comments.
   *
   * The purpose below is to show inline comments, note how the
   * fact that we only return the "positive" answer is highlighted.
   */
  function
  solve_quadratic_equation( A:int, B:int, C:int ) :   Number
   {
      return (-B + sqrt(B*B - 4*A*C)) / (2*A);  // NOTE: we only return the positive value
   }
            
          

C Language

            
  /**
   * The header for the function would go here, but see below
   * for examples of full header comments.
   *
   * The purpose below is to show inline comments, note how the
   * fact that we only return the "positive" answer is highlighted.
   */
  float
  solve_quadratic_equation(int A, int B, int C)
   {
      return (-B + sqrt(B*B - 4*A*C)) / (2*A); // NOTE: we only return the positive value
   }
            
          

Be aware, TOO MANY in line comments are as bad as too few. See the section below on self documenting code, which allows a programmer to minimize the number of necessary comments.


Self Documenting Code

Self documenting code uses well chosen variable names (and function names) to make the code read as close to English as possible. This should be your goal.

For example, naming a variable g has little meaning, but naming a variable gravity gives a much better description of what the variable should contain.

By using proper variable and function names, you should minimize the amount of "external" documentation that is necessary. For example, compare the following two pieces of code?

Cyrptic Matlab Code

            
% Poorly written/Cryptic code in Matlab 
[a1, a2] = slvqd(A,B,C);

fprintf('we got %f, %f', a1, a2);
            
          

Self Documented Matlab Code

            
[answer1, answer2] = solve_the_quadratic_formula(A,B,C);

fprintf('The solutions to Ax^2 + Bx + C = 0, are %f, %f', answer1, answer2);
            
          

File and Function Header Design Patterns

File Header comments are used to identify what is in a file, who wrote it, the date it was written, and a description of what is being solved by the code in the file. All program files should have header comments and it should be located at the TOP of the file!

The file header comment details what is in a file. Among other things it should have:

  1. The author, date, and course number.

  2. A description of what the code in the file accomplishes

  3. A list of any modifications (bug fixes) to the file. Note this is not as important for programs written in class, but important in the real world.

A good file header comment should fully describe the project and purpose of the code in the file. A programmer (or non-programmer for that matter) should be able to read the file header and be able to understand what is the high level idea and/or purpose behind the code, as well as what data-structures and methods are used. This can save many hours of time getting a new project member up to speed.

Function Header comments are used to describe the purpose of a function. Every function must have a separate header comment. Function headers serve to describe the algorithm which the function implements without forcing the reader to interpret code. Further, it serves to visually separate each function (e.g., in C, multiple functions are written in a single file).

Short and simple functions can have only a few lines of description. As a rule of thumb, the longer the function the longer the header comment.

Remember, always use appropriate amounts of whitespace and good formatting styles. This is as important in coding as in writing technical papers.

By using a function header, you will need to use fewer comments in the actual code segment of the function. This will make your program cleaner and more readable.

Here is an example of what one might expect:

Matlab Function/File Header

            
  %
  % function sorted_array = sort( array )
  %
  % Author1: H. James de St. Germain (germain@eng.utah.edu)
  % Author2: I worked alone 
  % Date:    Spring 2007
  % Course:  Computer Science 1000
  %
  % Function   : Sort
  %
  % Description: The Sort Procedure sorts an array of
  %              integers using the standard _bubble sort_ algorithm.
  %
  % Parameters : array              - a list of integers
  %
  % Return     : the newly sorted array
  %
  % Examples of Usage:
  %
  %    >> grades = [ 95 52 95 80 71 85 78 12 93 99 ];
  %    >> sorted_array = sort( array )
  %    ans =
  %           [ 12 52 71 78 80 85 93 95 95 99 ]
  %
  %

  function sorted_array = sort( array )
       ...
  end % of function
            
          

Matlab Script Header

            
   %
   %  File    :   name of file 
   %
   %  Author1 :   Programmer Name
   %  Author2 :   Programmer Name
   %  Date    :   Date created
   %
   %  Course  :   UofU course Number (e.g., CS1000)
   %  
   %  Description :  (in English, not Code)
   %                    
   %    1) What the purpose of the code is/what problem the code solves.
   %                    
   %    2) What data-structures are used.
   %                    
   %    3) What algorithms, techniques, etc, are used in this program
   %
   %  Examples of how to utilize the script, if appropriate, to help
   %  the next person to use your program, to more easily get it to work:
   %                    
   %
            
          

AS3 File Header

            
 /**
  * File:    compute_blackjack_odds.as
  *
  * Author1 :   Programmer Name
  * Author2 :   Programmer Name
  * Date    :   Spring 2007
  * Partner :   I worked alone 
  * Course  :   Computer Science 1410-EAE
  *
  * Description:
  *
  * This file contains code which simulates a blackjack game.
  * Functions allow the user of the software to play against the
  * "casino", or to simulate the odds of successfully "hitting"
  * given any two cards.
  *
  */
  
            
          

AS3 Function Header

            
 /**
  *
  * Summary of the Sort function:
  *
  *    The Sort function, rearranges the given array of
  *    Numbers from highest to lowest.
  *
  * Parameters   : array: containing integers
  *
  * Return Value : Nothing -- Note: Modifies the array "in place".
  *
  * Description  : The Sort function, rearranges the given array of
  *                integers using a standard bubble sort.
  *
  *
  */

  function sort( data : Array ) : void
  {
    // Code
  }
            
          

C File Header

            
 /**
  * File:    compute_blackjack_odds.C
  *
  * Author1:  H. James de St. Germain (germain@eng.utah.edu)
  * Author2:  Dav de St. Germain (dav@cs.utah.edu)
  * Date:     Spring 2007
  * Partner:  I worked alone 
  * Course:   Computer Science 1000
  *
  * Summary of File:
  *
  *   This file contains code which simulates a blackjack game.
  *   Functions allow the user of the software to play against the
  *   "casino", or to simulate the odds of successfully "hitting"
  *   given any two cards.
  *
  */
  
            
          

C Function Header

            
 /**
  *
  * void sort( int array[] )
  *
  * Summary of the Sort function:
  *
  *    The Sort function, rearranges the given array of
  *    integers from highest to lowest
  *
  * Parameters   : array: containing integers
  *
  * Return Value : Nothing -- Note: Modifies the array "in place".
  *
  * Description:
  *
  *    This function utilizes the standard bubble sort algorithm...
  *    Note, the array is modified in place.
  *
  */

  void
  sort( int array[] )
  {
    // code 
  }
            
          

Style

How one formats, indents, "prettifies" ones code so that it is Human Readable is very important. For more on see the section on Programming Style:


Back to Topics List