Best practices for writing code comments

[Ed. note: While we take some time to rest up over the holidays and prepare for next year, we are re-publishing our top ten posts for the year. Please enjoy our favorite work this year and we’ll see you in 2022.]

Famed MIT professor Hal Abelson stated: “Applications have to be written for folks to learn and solely by the way for machines to execute.” Whereas he might have purposely understated the significance of operating code, he’s spot on that applications have two very completely different audiences. Compilers and interpreters ignore feedback and discover all syntactically appropriate applications equally straightforward to grasp. Human readers are very completely different. We discover some applications more durable to grasp than others, and we glance to feedback to assist us make sense of them. 

Whereas there are lots of sources to assist programmers write higher code—reminiscent of books and static analyzers—there are few for writing higher feedback. Whereas it’s straightforward to measure the amount of feedback in a program, it’s onerous to measure the high quality, and the 2 should not essentially correlated. A foul remark is worse than no remark in any respect. As Peter Vogel has written:

  1. Writing after which sustaining feedback is an expense.
  2. Your compiler doesn’t verify your feedback so there isn’t any strategy to decide that feedback are appropriate.
  3. You’re, alternatively, assured that the pc is doing precisely what your code is telling it to.

Whereas all of those factors are true, it could be a mistake to go to the opposite excessive and by no means write feedback. Listed here are some guidelines that will help you obtain a cheerful medium:

Rule 1: Feedback shouldn’t duplicate the code.

Rule 2: Good feedback don’t excuse unclear code.

Rule 3: When you can’t write a transparent remark, there could also be an issue with the code.

Rule 4: Feedback ought to dispel confusion, not trigger it.

Rule 5: Clarify unidiomatic code in feedback.

Rule 6: Present hyperlinks to the unique supply of copied code.

Rule 7: Embody hyperlinks to exterior references the place they are going to be most useful.

Rule 8: Add feedback when fixing bugs.

Rule 9: Use feedback to mark incomplete implementations.

The remainder of this text explains every of those guidelines, offering examples and explaining how and when to use them.

Many junior programmers write too many feedback as a result of they had been educated to take action by their introductory instructors. I’ve seen college students in upper-division laptop science lessons add a remark to every closed brace to point what block is ending:

if (x > 3) 
 // if

I’ve additionally heard of instructors requiring college students to remark each line of code. Whereas this might be an affordable coverage for excessive learners, such feedback are like coaching wheels and ought to be eliminated when bicycling with the massive children.

Feedback that add no info have adverse worth as a result of they:

  • add visible muddle
  • take time to jot down and browse
  • can change into out-of-date

The canonical unhealthy instance is:

i = i + 1;         // Add one to i

It provides no info by any means and incurs a upkeep price.

Insurance policies requiring feedback for each line of code have been rightly ridiculed on Reddit:

// create a for loop // <-- remark
for // begin for loop
(   // spherical bracket
    // newline
int // kind for declaration
i    // identify for declaration
=   // project operator for declaration
0   // begin worth for i

One other misuse of feedback is to supply info that ought to have been within the code. A easy instance is when somebody names a variable with a single letter after which provides a remark describing its goal:

non-public static Node getBestChildNode(Node node) 
    Node n; // greatest baby node candidate
    for (Node node: node.getChildren())  utility(node) > utility(n)) 
            n = node;
    return n;

The necessity for feedback could possibly be eradicated with higher variable naming:

non-public static Node getBestChildNode(Node node) 
    Node bestNode;
    for (Node currentNode: node.getChildren()) 
        if (bestNode == null 
    return bestNode;

As Kernighan and Plauger wrote in The Elements of Programming Style, “Don’t remark unhealthy code — rewrite it.”

Probably the most notorious remark within the Unix supply code is “You are not expected to understand this,” which appeared earlier than some bushy context-switching code. Dennis Ritchie later defined that it was supposed “within the spirit of ‘This received’t be on the examination,’ slightly than as an impudent problem.” Sadly, it turned out that he and co-author Ken Thompson didn’t perceive it themselves and later needed to rewrite it.

This brings to thoughts Kernighan’s Law:

Debugging is twice as onerous as writing the code within the first place. Subsequently, in case you write the code as cleverly as doable, you might be, by definition, not sensible sufficient to debug it.

Warning readers away out of your code is like turning in your automobile’s hazard lights: an admission that you just’re doing one thing you understand is unlawful. As an alternative, rewrite the code to one thing you perceive effectively sufficient to elucidate or, higher but, that’s simple.

No dialogue of unhealthy feedback could be full with out this story from Steven Levy’s Hackers: Heroes of the Laptop Revolution:

[Peter Samson] was notably obscure in refusing so as to add feedback to his supply code explaining what he was doing at a given time. One well-distributed program Samson wrote went on for a whole bunch of assembly-language directions, with just one remark beside an instruction that contained the quantity 1750. The remark was RIPJSB, and other people racked their brains about its that means till somebody discovered that 1750 was the yr Bach died, and that Samson had written an abbreviation for Relaxation In Peace Johann Sebastian Bach.

Whereas I respect a great hack as a lot as the following individual, this isn’t exemplary. In case your remark causes confusion as an alternative of dispelling it, take away it.

It’s a good suggestion to remark code that another person would possibly take into account unneeded or redundant, reminiscent of this code from App Inventor (the supply of all of my constructive examples):

last Object worth = (new JSONTokener(jsonString)).nextValue();
// Notice that JSONTokener.nextValue() might return
// a price equals() to null.
if (worth == null || worth.equals(null)) 
    return null;

With out the remark, somebody would possibly “simplify” the code or view it as a mysterious however important incantation. Save future readers time and anxiousness by writing down why the code is required.

A judgment name must be made as as to whether code requires rationalization. When studying Kotlin, I encountered code in an Android tutorial of the shape:

if (b == true)

I instantly questioned whether or not it could possibly be changed with:

if (b)

as one would do in Java. After a bit of research, I discovered that nullable Boolean variables are explicitly in comparison with true with the intention to keep away from an unpleasant null verify:

if (b != null && b)

I like to recommend not together with feedback for widespread idioms until writing a tutorial particularly for novices.

When you’re like most programmers, you generally use code that you just discover on-line. Together with a reference to the supply permits future readers to get the total context, reminiscent of:

  • what downside was being solved
  • who supplied the code
  • why the answer is really useful
  • what commenters considered it
  • whether or not it nonetheless works
  • how it may be improved

For instance, take into account this remark:

/** Converts a Drawable to Bitmap. through */

Following the hyperlink to the reply reveals:

  • The writer of the code is Tomáš Procházka, who’s within the high 3% on Stack Overflow.
  • One commenter offers an optimization, already integrated into the repo.
  • One other commenter suggests a strategy to keep away from an edge case.

Distinction it with this remark (barely altered to guard the responsible):

// Magical system taken from a stackoverflow publish, apparently associated to
// human imaginative and prescient notion.
return (int) (0.3 * pink + 0.59 * inexperienced + 0.11 * blue);

Anybody trying to perceive this code goes to need to seek for the system. Pasting within the URL is far faster than later discovering the reference.

Some programmers could also be reluctant to point that they didn’t write code themselves, however reusing code could be a sensible transfer, saving time and providing you with the good thing about extra eyeballs. In fact, it’s best to never paste in code that you don’t understand.

Folks copy a lot of code from Stack Overflow questions and solutions. That code falls beneath Artistic Commons licenses requiring attribution. A reference remark satisfies that requirement.

Equally, it’s best to reference tutorials that had been useful, to allow them to be discovered once more and as due to their writer:

// Many due to Chris Veness at
// for an amazing reference and examples.

In fact, not all references are to Stack Overflow. Take into account:

// means that CSV traces
// ought to be terminated by CRLF, therefore the rn.

Hyperlinks to requirements and different documentation may help readers perceive the issue your code is fixing. Whereas this info could also be someplace in a design doc, a well-placed remark provides readers the pointer when and the place it’s most wanted. On this case, following the hyperlink signifies that RFC 4180 has been up to date by RFC 7111—helpful info.

Feedback ought to be added not simply when initially writing code but in addition when modifying it, particularly fixing bugs. Take into account this remark:

  // NOTE: A minimum of in Firefox 2, if the consumer drags outdoors of the browser window,
  // mouse-move (and even mouse-down) occasions won't be acquired till
  // the consumer drags again contained in the window. A workaround for this difficulty
  // exists within the implementation for onMouseLeave().
  public void onMouseMove(Widget sender, int x, int y)  .. 

Not solely does the remark assist the reader perceive the code within the present and referenced strategies, it’s useful for figuring out whether or not the code continues to be wanted and how you can check it.

It may also be useful to reference difficulty trackers:

// Use the identify because the title if the properties didn't embody one (difficulty #1425)

Whereas git blame can be utilized to search out the commit through which a line was added or modified, commit messages are typically temporary, and an important change (e.g., fixing difficulty #1425) will not be a part of the latest commit (e.g., shifting a way from one file to a different).

Generally it’s essential to verify in code though it has identified limitations. Whereas it may be tempting to not share identified deficiencies in a single’s code, it’s higher to make these express, reminiscent of with a TODO remark:

// TODO(hal): We're making the decimal separator be a interval, 
// whatever the locale of the cellphone. We want to consider 
// how you can permit comma as decimal separator, which would require 
// updating quantity parsing and different locations that rework numbers 
// to strings, reminiscent of FormatAsDecimal

Utilizing a normal format for such feedback helps with measuring and addressing technical debt. Higher but, add a difficulty to your tracker, and reference the problem in your remark.


I hope the above examples have proven that feedback don’t excuse or repair unhealthy code; they complement good code by offering a distinct kind of data. As Stack Overflow co-founder Jeff Atwood has written, “Code Tells You How, Comments Tell You Why.” 

Following these guidelines ought to prevent and your teammates time and frustration. 

That stated, I’m positive these guidelines aren’t exhaustive and look ahead to seeing recommended additions in (the place else?) the feedback.

Memes and cartoons

To your consideration…





Tags: comments

More Posts