Best practices for writing code comments - Deepstash

Bite‑sized knowledge

to upgrade

your career

Ideas from books, articles & podcasts.

published 10 ideas

Best practices for writing code comments

stackoverflow.blog

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 developer should be able to utilize a previously written program (or function) without ever having to look at the code, simply by readi...

3

STASHED IN:

9

"Programs must be written for people to read and only incidentally for machines to execute."

3

STASHED IN:

9

Your comments should be D.R.Y. The acronym stands for the programming maxim “Don’t Repeat Yourself.” This means that your code should have little to no redundancy. You don’t need to comment a piece of code that sufficiently explains itself. For example:

return a # Returns a

1

STASHED IN:

10

A misuse of comments is to provide information that should have been in the code. An example is when someone names variables badly and then tries to add comments describing them:

# A dictionary of families who live in each city

mydict = {

"Midtow...

1

STASHED IN:

9

The most infamous comment in the Unix source code is “You are not expected to understand this,” which appeared before some hairy context-switching code. It turned out that Dennis Ritchie and co-author Ken Thompson didn’t understand it themselves and later had to rewrite it.

Warning readers ...

1

STASHED IN:

9

It’s a good idea to comment code that someone else might consider unneeded or redundant, such as this code:

final Object value = (new JSONTokener(jsonString)).nextValue();

// Note that JSONTokener.nextValue() may return

// a value equals() to nu...

1

STASHED IN:

9

Most programmers use code that they find online. Including a reference to the source enables future readers to get the full context, such as:

  • what problem was being solved
  • who provided the code
  • why the solution is recommended
  • what commenters thought of it

1

STASHED IN:

9

Comments should be added not just when initially writing code but also when modifying it, especially fixing bugs. Consider this comment:

// NOTE: At least in Firefox 2, if the user drags outside of the browser window,

// mouse-move (and even mouse-down) events will ...

1

STASHED IN:

8

Sometimes it’s necessary to check in code even though it has known limitations. While it can be tempting not to share known deficiencies in one’s code, it is better to make these explicit, such as with a TODO comment:

// TODO: We are making the decimal separator be a period,

1

STASHED IN:

9

0 Comments

Discover and save more ideas by creating a

FREE

Deepstash account.

Develop a

reading habit

, save

time

and create an amazing

knowledge library

.

GET THE APP: