My CS professor "hates" comments in code. Is that really a thing?

"Self documenting code" is a controversial thing among professional programmers. Without going into a big long story about how exactly you should comment, I would just like to say that it's not the prevailing opinion that code should have no (or almost no) comments.

However, there is a grain of truth to it. For example, you should never write a comment for this:

y += 3; // add 3 to y

What the line does is obvious to anyone who knows the programming language. So this code, without the comment, is definitely "self documenting" and should not need commentary.

However, the problem is when you take it too far. A lot of code DOES need comments, because while it's easy to understand every individual line, it's difficult to understand what the lines do collectively. Generally, people take "self documenting code" too far, and when they refer to it as such they refer to code that has too few comments. I'm not sure if that's what your teacher means, though.

I would stick with this basic principle: don't add comments that are obvious to anyone who knows the language. But in all other cases, by all means, it's better to add too much documentation than too little. Especially add comments that clarify why a piece of code does something if it isn't obvious, and make note of the nature of the data a function takes and outputs.

Here's an example of something I wrote recently:

export const requireAuth = (nextState, replace) => {
  // Don't redirect if we're logged in or if we're going to the login page.
  if (store.getState().auth.isLoggedIn || nextState.location.pathname === '/login') {
    return;
  }

  // Redirect to /login, keeping the next URL in mind when we finish the login process.
  replace('/login', null, { nextPathname: nextState ? nextState.location.pathname : '/' });
};

This is a really simple function. It has one if with two checks, and if it doesn't return it just runs one other function. But the comments are invaluable because why we are doing these checks is not clear.

/r/learnprogramming Thread