Commenting Methods

From CompSciWiki
Jump to: navigation, search

COMP 1010 Home > User-Defined Methods

Introduction

Describing a method using comments is different from commenting actual code. The comments that describe a method should explain the overall purpose of the method, the meanings of the parameters, and what the return value represents. This section covers a standard way of commenting user-defined methods.

Commenting Methods

The COMP1010 Java Standards site describes how user-defined methods need to be commented for assignments.

Every method (except main) must begin with a prologue comment, similar to the following:

 /**
 * Describe the purpose of the method. Clearly.
 *
 * @param firstParameter  description of what firstParameter means
 * @param secondParameter description of what secondParameter means
 *                        and so on, for all the parameters...
 *
 * @return                what is the meaning of the return value?
 */ 

Parts of the prologue may be omitted if appropriate, e.g. if the method has no parameters.

A complete comment block describes the method, explains the parameters, and states what the return value means. Using this standard commenting format provides two benefits:

  1. Anyone who calls your method can see what your method does at a glance.
  2. Anyone who calls your method has all the information they need to use your method.

Here's an example of a comment block for a temperature converting method:

 /**
 * This method converts a Fahrenheit temperature to a Celcius temperature
 *
 * @param fahrenheitTemp - The Fahrenheit temperature to convert into Celcius
 *
 * @return double celciusTemp - The calculated Celcius temperature
 */
 public static double convertToCelcius(double fahrenheitTemp)
 {
     double celciusTemp;
     celciusTemp = (fahrenheitTemp - 32) * 1.8;
     return celciusTemp;
 } 

Now imagine that you want to convert temperatures, but you do not know the formulas for doing so. If you have access to the above method, you only need to know what the method does and not how the method is coded.