Best practices for writing code comments - Deepstash
Best practices for writing code comments

Best practices for writing code comments

10 ideas


403 reads


Machine Learning With Google

Learn more about computerscience with this collection

Understanding machine learning models

Improving data analysis and decision-making

How Google uses logic in machine learning

Machine Learning With Google

Discover 95 similar ideas in

It takes just

14 mins to read

Commenting involves placing Human Readable Descriptions inside of computer programs detailing what the Code is doing. Proper use of commenting can make code maintenance much easier, as well as helping make finding bugs faster. Further, commenting is very important when writing functions that other people will use. Remember, well documented code is as important as correctly working code.

While it's easy to measure the quantity of comments in a program, it's hard to measure the quality, and the two are not necessarily correlated. A bad comment is worse than no comment at all.


146 reads


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 reading the comments.

Commenting is the "art" of describing what your program is going to do in "high level" English statements.


61 reads

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



54 reads

Comments should not duplicate the code (D.R.Y)

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

We can clearly see that 'a' is returned, so there’s no need to explicitly state this in a comment. It adds no information whatsoever and incurs a maintenance cost. This makes comments W.E.T., meaning you “wrote everything twice.”


24 reads

Good comments do not excuse unclear code

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 = {

"Midtown": ["Powell", "Bran"],

"Norcross": ["Mont"]


def a(dict):

# For each city

for p in dict:

# If there are no families in the city

if not mydict[p]:

# Print it


This script could have been made simpler by using obvious names for variables, functions and collections.


25 reads

If you can’t write a clear comment, there may be a problem with the code

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 away from your code is like turning on your car’s hazard lights: an admission that you’re doing something you know is illegal. Instead, rewrite the code to something you understand well enough to explain or, better yet, that is straightforward.


16 reads

Explain unidiomatic code in comments

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 null.

if (value == null || value.equals(null)) {

return null;


Without the comment, someone might “simplify” the code or view it as a mysterious but essential incantation. Save future readers time and anxiety by writing down why the code is needed.


32 reads

Provide links to the original source of copied code

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
  • whether it still works

For example, compare the follwowing pieces of code:

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


// Magical formula taken from a stackoverflow post, reputedly related to

// human vision perception.

return (int) (0.3 * red + 0.59 * green + 0.11 * blue);


16 reads

Add comments when fixing bugs

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 not be received until

// the user drags back inside the window. A workaround for this issue

// exists in the implementation for onMouseLeave().

@Override public void onMouseMove(Widget sender, int x, int y) { .. }

This helps the reader understand the code and it is helpful for determining whether the code is still needed.


17 reads

Use comments to mark incomplete implementations

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,

// regardless of the locale of the phone. We need to think about

// how to allow comma as decimal separator, which will require

// updating number parsing and other places that transform numbers to strings

Using a standard format for such comments helps with measuring and addressing technical debt.


12 reads


Explore the World’s

Best Ideas

200,000+ ideas on pretty much any topic. Created by the smartest people around & well-organized so you can explore at will.

An Idea for Everything

Explore the biggest library of insights. And we've infused it with powerful filtering tools so you can easily find what you need.

Knowledge Library

Powerful Saving & Organizational Tools

Save ideas for later reading, for personalized stashes, or for remembering it later.

# Personal Growth

Take Your Ideas


Organize your ideas & listen on the go. And with Pro, there are no limits.

Listen on the go

Just press play and we take care of the words.

Never worry about spotty connections

No Internet access? No problem. Within the mobile app, all your ideas are available, even when offline.

Get Organized with Stashes

Ideas for your next work project? Quotes that inspire you? Put them in the right place so you never lose them.


2 Million Stashers


5,740 Reviews

App Store


72,690 Reviews

Google Play

Sean Green

Great interesting short snippets of informative articles. Highly recommended to anyone who loves information and lacks patience.

Shankul Varada

Best app ever! You heard it right. This app has helped me get back on my quest to get things done while equipping myself with knowledge everyday.

Ashley Anthony

This app is LOADED with RELEVANT, HELPFUL, AND EDUCATIONAL material. It is creatively intellectual, yet minimal enough to not overstimulate and create a learning block. I am exceptionally impressed with this app!


Don’t look further if you love learning new things. A refreshing concept that provides quick ideas for busy thought leaders.

Ghazala Begum

Even five minutes a day will improve your thinking. I've come across new ideas and learnt to improve existing ways to become more motivated, confident and happier.

Giovanna Scalzone

Brilliant. It feels fresh and encouraging. So many interesting pieces of information that are just enough to absorb and apply. So happy I found this.

Laetitia Berton

I have only been using it for a few days now, but I have found answers to questions I had never consciously formulated, or to problems I face everyday at work or at home. I wish I had found this earlier, highly recommended!

Jamyson Haug

Great for quick bits of information and interesting ideas around whatever topics you are interested in. Visually, it looks great as well.

Read & Learn

20x Faster





Access to 200,000+ ideas

Access to the mobile app

Unlimited idea saving & library

Unlimited history

Unlimited listening to ideas

Downloading & offline access

Personalized recommendations

Supercharge your mind with one idea per day

Enter your email and spend 1 minute every day to learn something new.


I agree to receive email updates