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

closed as primarily opinion-based by TMN, Robbie Dee, Ixrec, Adam Zuckerman, gnat Apr 18 '16 at 6:00

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 14
    It's going to be difficult to give good answers to this, since the example comment is describing things that are completely obvious from the code anyway. – Sebastian Redl Apr 15 '16 at 8:01
  • 2
    I agree with @SebastianRedl that those things are completely obvious from the code (if they aren't, the person reading the comments has a much bigger problem than whether comments should be phrased as descriptions or as orders). Also, iterate over it is quite a useless comment, it should explain "iterate to do what". IMO comments should mainly be used to link the business logic to the code, f.ex. We have the articles in the array. Iterate over it to find the one with the requested id. – SantiBailors Apr 15 '16 at 8:08
  • 1
  • If the triviality is not the real question, just change "array" to some domain information model term, and "iterate" to some complex process. But... that should still be done with names and organization of the actual code instead! So it's hard to make up an example. Maybe find something real to relate? – JDługosz Apr 15 '16 at 9:14
  • 1
    @gnat ... true dat. I tend to get a bit defensive towards the new guys. That said a bit of google-fu level 1 could easily have found good answers without ever really asking out loud. – Newtopian Apr 15 '16 at 14:03
10

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.

  • Thanks....this and @Benn Cotrell's answer helped a lot... :-) – rahil008 Apr 19 '16 at 8:59
41

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.

  • 1
    I'm in agreement with you. Comments at code are like hints. Notes for developers to make easier to understand why. Plus It's the best way to put references to the Issues that caused such implementation: //Issue #0000: Due to... bla bla bla – Laiv Apr 15 '16 at 8:36
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.

  • Comments stating business purpose/ high-level purpose are very worthwhile -- they confirm & support understanding of the code's purpose. I prefer to keep them, despite some claiming "redundancy". Remember that unit tests are "redundant" also. – Thomas W Jun 12 '17 at 23:30
4

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

1

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.

  • Strongly disagree with "Comments shouldn't even really explain why". Comments are usually the only way for a developer who is unfamiliar with the code to understand the rationale behind it. Somewhere along the line a developer picking up a bit of existing code needs to understand not only which requirements and user expectations it satisfies, but also the assumptions that the original developer made when they wrote the code. All of this is part of the "WHY"; and the absolute best place for that rationale is in the code comments. – Ben Cottrell Apr 16 '16 at 10:18
  • I'm not saying the "why" shouldn't be communicated. I'm saying that when the only place you can actually do this is in comments, then you have failed and need to reflect on why this happened. Code is a better place for "why". So are tests. So are domain knowledge. Just about everything is a better place for "why" than comments, because comments aren't compiled, so they lie and they bloat. sometimes they are a necessary evil, but they are still evil and should be avoided when at all possible. – sara Apr 16 '16 at 12:04
  • Code doesn't explain rationale; which are all the things in a developer's head while they're writing code. Code simply documents its own design and what it does. For example, a line of code might be necessary due to some peculiarity of a 3rd-party library, or maybe the code is part of a series of steps in a workflow which isn't obvious from reading the code, or maybe there are known limitations/constraints which affect the system. There are many, many things which developers "think" while writing code which is impossible to capture in the code itself, so the "Why" has to go into comments. – Ben Cottrell Apr 16 '16 at 12:27
  • External documentation is not appropriate for explaining why individual bits of code do a certain thing, because you would need a way of referencing the bit of code which they talk about; and since code tends to change, that would make the documentation go out of date. So really the best place to put that information is within comments in the code itself. – Ben Cottrell Apr 16 '16 at 12:33
  • This is why I didn't mention external documentation, because it has similar problems to comments. Although I'd argue that external docs might even have some one-ups on comments in certain cases, since they tend to be more formal. it depends on your team/workflow though. What I argume is cementing intent in the one place where it can't be neglected or incorrect: in the code itself. And again, sometimes you don't know how or don't have the time to do that. In those cases, bite the sour apple and vow to fix it asap, and try to learn how to avoid that nasty comment next time. – sara Apr 16 '16 at 12:47

Not the answer you're looking for? Browse other questions tagged or ask your own question.