4

I was wondering how one should write comments in code. I mean, should a comment be a descriptive of what is done in code, like : //we have got array, now we iterate over it. code to iterate array

or should it be telling what we should do here. like an order, like : //we have got array, iterate over it. code to iterate array

Doc Brown
  • 218,378

5 Answers5

42

Neither. Comments should not describe what code does (at the same level of abstraction as the code itself), but only why it does something

Don't take this too literally, this is a guideline, if you write a short summary what a longer piece of code will do, that may be acceptable. However, comments describing obvious things like "this is an iteration" should be avoided, they don't make the code better readable or understandable, add only clutter, and they violate the DRY pinciple.

Doc Brown
  • 218,378
29

The comments you write are fine for demonstration code when teaching a new language for beginners. They're the equivalent of "See Jane run. Run, Jane, run!"

But in every other settings they're not appropriate. Every habitual programmer would just be puzzled, thinking "Huh? Why are you telling me this when it's already utterly obvious what's going on? Is there something non-obvious going on that I'm missing?"

A novel author doesn't write "Jane left he building and walked down the street, systematically putting one foot in front of the other." He'd write "Jane went to the department store", or even "when Jane arrived at the department store, she..." or even just "Having finished with her shopping, Jane relaxed..."

Similarly, a professional progammer wouldn't write

// Iterate over the array
for(int x: ai) { ...

but at most

// notify all observers
for(int x: ai) { ...

or even just

notifyObservers()

where the actual code is hidden in a subroutine with a meaningful name.

Kilian Foth
  • 110,899
9

Overview what the code is about. It may be obvious when you write it, but not two years later, so write down when this code is used in the application, why it is used and so on. Like "this code handles the situation where a user fills out a form complaining about returned packages lost in the post". Answers the question "what the hell is this code for".

If it isn't obvious, a high level overview how the code works.

Comments in header files (or in places where they get automatically extracted) so that for every public function, a reader will know what it does and why it should be called without referring to source code.

Especially for virtual functions: Comments in header files what this function, including overrides, is supposed to do. For non-virtual functions the comments are a convenience, saving me from reading source code. For virtual functions, there is no source code.

Comments that tell other developers when you do something that looks weird. There are places where my code contains some lines that look like absolute nonsense, and then there's a comment "Works around a bug in library XYZ".

Comments explaining what the code does in terms of the problem that is solved. Like "find all customers who purchased items worth less than $100 in the last year and made more than three returns" - this might not be obvious from the code.

"We have got array, iterate over it" as a comment for code iterating over an array is nonsense. I can see that you are iterating, I don't need a comment for that. Tell me what the iterating is actually doing.

gnasher729
  • 49,096
5

Comments are for communicating any information to future developers who are either using or maintaining the code, which is not obvious from reading the code.

When writing comments, consider the situations facing a new developer who is unfamiliar with your code, and your present mindset.

While you're writing code, you're usually juggling a lot of balls in your head, trying to avoid potential pitfalls; and your comments should reflect the things you're juggling, because it's most likely to be information that any future developer will also need to know to avoid making mistakes. For example:

// A user could potentially type an invalid username here but we can't
// validate it yet because we need to support the legacy login format.

or

// We don't know whether the server is available yet, but we don't care
// until the user does something which involves a message to the server.

or

// Always use the FooFactory for creating Foo objects because it guarantees
// they will be initialised using the correct Config.

or

// This calculation is only an approximation until the customer can 
// supply us with the correct logic, so we know it's wrong, but the
// customer confirmed they are happy with it as an interim measure. 

or

// HACK: this function fixed a critical fault identified while on XYZ customer site.  
// This is currently in use by XYZ, it must be refactored into a generic solution ASAP.
// see ticket #12345 in the bugtracking system.

or

// This function may fail if VehicleType==Train, but there are currently no 
// documented requirements or data for Trains, so there's no way to reliably test it.

So when trying to decide what kind of comments to put in your code, take several steps back from the code itself and think about all the problems you've faced, the assumptions you've made, the compromises you've made, etc.

The comments should be a rationale which captures "Why did I write this code in this particular way at this particular time?". The reality is that code is usually never 'finished', code tends to evolve constantly, it tends to be constrained by real-world issues (deadlines, customer demands, budget, etc). so it will always have warts and imperfections which are beyond the developer's control.

Your comments are the best place to document those things - avoid writing long essays, just stick to the minimum amount of information which might warn future developers away from making mistakes, or even just let them know that you've already considered the benefits/limitations of your solution (or even if you've found potential issues with someone else's existing code and haven't been able to fix it).

Ben Cottrell
  • 12,133
2

I think the answer for your specific example is neither. Comments shouldn't explain what the code does. The CODE should explain what the code does. Comments shouldn't even really explain WHY it does it, that should be either obvious with even slight domain knowledge or with technical knowledge.

This second part is hard sometimes though. Sometimes you find some obscure bug or a really weird quirk in some framework you're using. The "obviously better code" might actually be worse, than the current weird looking code, and in those cases it is of course OK to make an exception and add a comment explaining the situation.

This should be viewed as a failure though. It is something to be avoided, because like others have alluded to, comments are mostly redundant. The VERY rarely actually give any value. But violating DRY isn't even the worst part. The worst part with comments is that they are not code, so they are not executed and therefore the reader has NO proof whatsoever that the comment has anything to do at all with reality.

Comments get old, they have mistakes, they get orphaned, the author might be mistaken, etc. They are notoriously deceptive. Even if you see a comment saying "this code block does X", you can't REALLY trust that it does X without looking at it.

If you feel that the algorithmic structure of your code is hard to see at a glance, the solution is not to add 20 comments. It's to restructure/refactor the code so it's separated into small concise logical units with good method names. Use the patterns we all learn. Encapsulate things. Design a good architecture, don't cover up a bad one by sticking post-its all over the place.

EDIT: Just to clarify since some people seem to have misinterpreted: I'm not saying you should never use comments. I'm saying that you really really really shouldn't want to because they bring lots of problems. I'm saying that sometimes you have to, but you should try to find a better solution.

sara
  • 2,579