See All Blog Posts

Great Code Comments

  


Great Code Comments


In this blog post, we'll explore why and how you should write comments in your code. Share this with your students!

Why Comment Code?

There are several classic reasons why code comments are important.

  • Remind Yourself - You may not remember exactly how or why you solved a problem in code when you look back weeks or months later. Comments help you understand your own work.
  • Help Others - Other programmers may review your code or need to make changes, and teachers might read your code to assign a grade. Help them understand what you're doing.
  • Explain Tricky Parts - Sometimes a complex problem will have a clever solution. Explain that solution in ways that make sense when the code is not obvious.
  • Generate Auto-Docs - Some languages have tools (like JavaDoc) that can automatically create nicely formatted HTML or other documents from your code comments. Add specially formatted comments to support these tools.

Classroom Considerations

Great Code CommentsIn a classroom setting, students often produce similar code that works the same way to meet the requirements of an assignment. To help identify a student as the author, students may want to put their name, class, and assignment info at the top of source files in a comment.

/* Computer Programming I, 5th Period
   Chapter 10 Activity: DogHouse Project
   Student Name
   Date
   This file contains the Dog class
*/

In today's age of ChatGPT and other AI assistants, how does your teacher know the submitted work is uniquely yours? Adding your own, creative commentary about the code demonstrates that you know exactly what's going on and supports your claim that you've completed the assignment on your own.

Professional Considerations

Software engineers will write many thousands of lines of code. That code might be shared, reused, or modified by yourself or others over time. What happens if you are asked to take over someone else's work and their code is poorly written with no comments? You'll have a much harder time understanding how to make changes. Software companies will often have coding standards that detail how and when comments should be added to source files.

The overall appearance of your code is also important! As a professional, you may be judged not only on how well your code works, but how easy it is to maintain. Code that is neat, follows standards for white space and formatting, and contains good comments will reflect well on the author. But if you write code that is hard to understand, good luck getting a raise or promotion later!

Adding Value with Comments

One of the biggest reasons to add comments is to provide some knowledge of value to the person reading them. Consider this example:

Not Helpful

// this method wakes the dog up
public void wakeUp() 
{
   System.out.println("WAKING UP"); // prints a message to the screen
   sleeping = false;                // sets the value of sleeping to FALSE
   numTimesFed = 0;                 // sets the number of times fed to 0
}

The author has dutifully commented above the function header and on every line of code. However, the comments don't add any value to the reader, because they are an obvious restatement of the code.

Here is the same code with more helpful comments. The comments detail what the function does or why each statement is written.

More Helpful

// When a dog wakes up, print a message and reset daily properties
public void wakeUp() 
{
   System.out.println("WAKING UP"); // required status output
   sleeping = false;                // note that the dog is no longer sleeping
   numTimesFed = 0;                 // starting each morning, this dog has not yet been fed
}

}

Here's another example where the comments describe some logic in human terms. Imagine trying to understand how the race car's speed is adjusted by the accelerate() method without the comments!

// increase RaceCar’s speed (required by the IRacer interface)
public void accelerate() 			
{
   // accelerating means we increase current speed by acceleration value
   myCurrentSpeed += myAcceleration; 			

   // has car exceeded maximum speed?
   if (myCurrentSpeed > myMaxSpeed) 						
   {
      // cap current speed at maximum speed
      myCurrentSpeed = myMaxSpeed; 		
   }
}

Other Tips

Which set of comments below is easier to read? Using white space to neatly line up your comments allows the eye to easily separate and read the comments apart from the code.

myDog.wakeUp(); // tell the dog to wake up
myDog.hear(name); // the dog hears his name and will wag his tail
myDog.hear("ding-dong"); // the dog hears the door bell and will bark
myDog.hear("mailman's voice"); // the dog hears the mailman and will chase him
myDog.hear("other sound"); // the dog won’t do anything for other sounds
myDog.feed(); // tell the dog to eat
myDog.feed(); // dog will yawn after this second feeding
myDog.wakeUp();                // tell the dog to wake up
myDog.hear(name);              // the dog hears his name and will wag his tail
myDog.hear("ding-dong");       // the dog hears the door bell and will bark
myDog.hear("mailman's voice"); // the dog hears the mailman and will chase him
myDog.hear("other sound");     // the dog won’t do anything for other sounds
myDog.feed();                  // tell the dog to eat
myDog.feed();                  // dog will yawn after this second feeding

If you are implementing an algorithm, interface, or logic that is fully described in some external document or web page, then adding a link to that description in a comment is a great idea.

public void optimize(int[] data)
{
   // This function implements the Spaghetti optimization algorithm described here:
   // https://www.egghead.com/papers/optimization/spaghetti_algorithm.php
}

Finally, we'll mention that many languages have tools that can scan your source code and produce automated reference documents or web pages from specially formatted comments. JavaDoc for the Java language is a great example. JavaDoc comments start with /** and end with */.

/** Java Programming<br>
 * Chapter 02 - Show Time<br>
 * The ShowTime class will print the current time to the console<br>
 * @author CompuScholar, Inc.
 * @version 1.0
*/
public class ShowTime
{
   /** The main function will run our single line of code, which will output the current time
     * @param args These are the command line arguments supplied to the program
     *
     */
   public static void main(String[] args)
   {
      System.out.println(Calendar.getInstance().getTime());
   }
}

The JavaDoc tool can turn these comments into web pages with standardized documentation.

JavaDoc output

For More Information

Check out our March 2024 Professional Development Webinar - "Great Code Comments" - for further details and a video discussion. As always, please Contact Us if you have questions!