Search results

Tips for writing code comments in developer documentation

by Tom Johnson on Jan 11, 2014
categories: api-doc

I used Grammarly's proofreading software because my eyes become blind to errors after I read through the same post several times.

When you write documentation for programming code, such as APIs and SDKs, you become accustomed to writing and editing code comments. Code comments are explanatory text mixed with programming code to explain what's going on in the code. For example, here might be a code comment for a JavaScript function:

<p>function shout (x,y) {</p>
<p>// remember to do division before addition</p>
<p>    if (x + y > 4 + 8 / 2 ) {<br />
       alert('hello')<br />
    }<br />
    else {<br />
       alert('bye')<br />
    }<br />
}<br />

You wouldn't usually comment on such a simple function, but "simple" is always a subjective statement. What is simple for one person may be complicated for another. So as always, the level of commentary depends on the level of the audience.

The wp-config.php sample file for WordPress provides a highly commented file. In it you see code comments like the following:

<p>/**<br />
* For developers: WordPress debugging mode. *<br />
* Change this to true to enable the display of notices during development.<br />
* It is strongly recommended that plugin and theme developers use WP_DEBUG<br />
* in their development environments.<br />
<p>define('WP_DEBUG', false);</p>

As you can see, this comment is much lengthier, because define isn't likely a familiar function to programmers (it's just a WordPress specific function).

As another example, see the code samples Sarah Maddox linked to in her recent post on How to write sample code.

Comment styles vary widely

Comments in code can take all varieties. Some programmers inject humor or sarcasm. Others are terse or cryptic.

Some people feel you can be less formal and even playful in code comments, and I agree. The comment domain tends to be within the programmer's realm, so you find the same spirit in code comments as you do in the early days of the web -- irreverence, transparency, bluntness. You can use all lowercase if you want, omitting ending punctuation.

In Learning JavaScript: A Hands-on Guide to the Fundamentals of Modern JavaScript, Tim Wright explains why he welcomes humor in code comments:

Coding can always be a little more stressful than we would like, so don't be afraid to inject some humor into your comments. As far as brightening up someone's day when they're eyeballs deep in code, it doesn't get much better than reading a funny comment someone left. I've even caught myself laughing at comments I've written in the past. It's always a nice surprise and lightens the mood. (Chapter 9: Code Design)

In other words, playful comments help lighten the programmer's mood. (Wright's book, by the way, is probably the best book on JavaScript I've read.)

Regardless of the tone you adopt, generally if there's an element of the code that needs some explanation (because it's unintuitive or a tricky workaround, or it involves elements new to the user), the programmer usually notes the reason in a comment.

Are code comments useful?

Some people object to the usefulness of code comments, arguing that code is "self-documenting."

The idea is that if the code isn't immediately apparent to the user, no amount of commenting is going to solve the problem. Code relies on specific functions and techniques, and if one is familiar with programming, code that doesn't do anything strange needs no explanation.

In short, readers should become acquainted with programming, and they will immediately understand what's going on -- without comments. Comments just tend to get in the way. Code only needs explaining when the code is written in such a confusing way that comments are needed to make sense of it.

On Coding Horror, Jeff Atwood says not to add too many comments:

Junior developers rely on comments to tell the story when they should be relying on the code to tell the story. Comments are narrative asides; important in their own way, but in no way meant to replace plot, characterization, and setting. (Coding Without Comments)

In other words, comments are kind of like an abundance of footnotes in a poorly written essay. If there are 5+ footnotes per page that clarify and summarize/expand on every paragraph, as a reader you may wonder why the writer didn't just write the essay clearly in the first place, without forcing readers to wade through all of this side commentary.

The same thing happens with code. Well-written code tells its own story. When things are organized clearly, when you have the right white spacing, line breaks, and other code formatting, when your logic proceeds plainly, when variables are defined well, you shouldn't need commentary explaining what's going on.

Others don't feel this same way about code. They recognize that not everyone is a programming genius and so leave notes and instruction to the reader. Or they understand that their audience will be unfamiliar with the techniques and concepts, and so the comments are a form of instruction to help others understand.

This latter scenario -- the teaching scenario -- is much more common with documentation. If you're writing a code sample to help others understand how to work with your API or SDK, you assume many of the methods, arguments, techniques, etc., are going to be unfamiliar to the reader, no matter what the reader's skill level. As such, comments are needed.

However, even if you're trying to teach someone, if you add too many comments, the code becomes unreadable. Adding a comment about every 5 lines of code seems to be a good balance. The comments must always be brief (e.g., usually 1-2 lines) because the reader is primarily looking at the code, not the comment, and any lengthy comment will make it harder to see the code for itself because the comments separate arguments and functions that usually fit together.

Another detail to keep in mind is that code isn't always linear. You may declare variables or refer to functions at the beginning of code that aren't used or listed until later in the code. As such, the comments you add may not provide a linear story to narrate what's happening in the code. This is another reason why code comments are best left brief: you really can't tell the full story of what the code is doing in these brief comments.

Code comments as a microcosm of technical communication

Code comments are more than just a stylistic decision. How to comment on code fits into a larger discussion about how to explain programming code in general.

A lot of technical writers pride themselves on their ability to simplify complexity, but programming code presents a new level of complexity. It's complex because the code relies on a host of methods, concepts, and techniques that may be unfamiliar to the user.

For example, a code sample I created the other day included a jQuery method called $.map. It takes two arguments as its input: first an array, and then the function to apply to the array. It outputs a new array based on what the function does to the array.

When a programmer first said I should use it, I had never heard of it. In my commentary on the code, I explained the method as if it would be new to the reader. But most likely my ignorance works against me here. A JavaScript developer, especially one using jQuery, has probably used $.map many times before. My explanation may only draw questions for the reader, prompting him or her to wonder why I'm explaining such a common method.

This is just one example of dozens of decisions you must make when adding code comments. What is familiar to the reader and what is not? When you aren't the audience, it can be a tough judgment call. Other engineers who review your code can give you feedback, but they too are trapped by their own perspective.

For example, the other day an engineer crossed out a whole section I'd written about the em properties. I had noted that if you use em in CSS, its value is relative to the font-size set on the parent container. If no font size is set on the parent, the size inherits the next parent up until the body tag. If no size is set on body, em inherits the browser default for font-size, which is usually 16px.

The engineer said that anyone who works with CSS will know this, so it is unnecessary. Yet the following week I received a request for more detail about the font-size and inheritance, since the user -- not a developer -- was unfamiliar the concept.

The conundrum of knowing your audience is that your audience is often not homogenous. Your audience most likely has a variety of skills and abilities, so what's familiar to one is unfamiliar to another. Clearly you can't write for a third-grade level as well as a senior programmer and hope to satisfy both with the same set of information, but you can provide different paths through the same content.

When I comment on code, I usually create those paths by doing the following.

First, I briefly summarize the code and how it works in 1-2 paragraphs. I then present the code block with brief code comments. After the code block, if needed I provide a story-like explanation that proceeds section by section with lengthier details and references.

The introduction and code comments will appeal to the experienced programmer. The lengthier code explanation below the code will appeal to the novice programmer. In this lengthier explanation, I'll explain what we're trying to do and then show the code used to accomplish the ends (approaching it more as a narrative) rather than as after-the-fact signposts.

Within the longer commentary, I try to link out to additional explanations. For example, rather than trying to explain the $.map function beyond a couple of brief sentences, I would link to jQuery's explanation of their own feature.

I know the experienced programmer usually doesn't read beyond the initial code sample, which is fine. I'm not expecting the experienced programmer to read the code explanation at all.

In sum, writing code comments may seem like a trivial exercise, but it really gets to the heart of what technical writing is all about -- explaining complicated material and layering your explanation for a variety of audiences.

This post was sponsored by Grammarly.

About Tom Johnson

Tom Johnson

I'm an API technical writer based in the Seattle area. On this blog, I write about topics related to technical writing and communication — such as software documentation, API documentation, AI, information architecture, content strategy, writing processes, plain language, tech comm careers, and more. Check out my API documentation course if you're looking for more info about documenting APIs. Or see my posts on AI and AI course section for more on the latest in AI and tech comm.

If you're a technical writer and want to keep on top of the latest trends in the tech comm, be sure to subscribe to email updates below. You can also learn more about me or contact me. Finally, note that the opinions I express on my blog are my own points of view, not that of my employer.