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
  • 199,015
  • 33
  • 367
  • 565
rahil008
  • 59
  • 1
  • 1
  • 4
  • 15
    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 08: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 08:08
  • 1
    See also: http://programmers.stackexchange.com/questions/175020/what-is-the-best-approach-for-inline-code-comments – Doc Brown Apr 15 '16 at 08:13
  • 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 09:14
  • Oh, is commenting grammar really specific to Java? – JDługosz Apr 15 '16 at 09:15
  • Code as if you couldn't use comments at all and you won't go far wrong. – Robbie Dee Apr 15 '16 at 09:59
  • related (possibly a duplicate): [Should comments say WHY the program is doing what it is doing?](http://programmers.stackexchange.com/questions/173118/should-comments-say-why-the-program-is-doing-what-it-is-doing-opinion-on-a-dic) – gnat Apr 15 '16 at 10:09
  • To all the downvoters : I often see (very) green programmers wondering where and how to comment the code. Especially since it is often a requirement of the teacher asking for the assignment. I also often see these teachers asking that EVERY LINES be commented which the student sees as something that is very important to the art. In this context this question is VERY relevant if only to break this impending niagara falls of commented code and actually get it right. Doc Brown provide a good answer but Kilian's really drives it home with the example I think. – Newtopian Apr 15 '16 at 13:49
  • @Newtopian ...if only this wasn't discussed here many times before. See eg [very first question at this site](http://programmers.stackexchange.com/questions/1/comments-are-a-code-smell) posted over 5 years years ago, about 30 questions linked to it and who knows how many more questions that are linked to these 30 – gnat Apr 15 '16 at 13:56
  • 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
  • The best way of writing comments in code is to don´t write comments at all – Alex B. Apr 15 '16 at 15:40

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
  • 199,015
  • 33
  • 367
  • 565
  • 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 08: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.

Kilian Foth
  • 107,706
  • 45
  • 295
  • 310
  • 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
  • @ThomasW ATs are also good for that. And will break if the behavior of said code changes, unlike comments. – user2051770 Feb 18 '22 at 14:49
  • @user2051770 Theoretically they could, but in my experience automated tests are rather commonly written as a bunch of undocumented and highly opaque mocking, state setup and assertions. These don't add almost any documentary value and frequently test the specifics of one particular impl, rather than any general contract. I don't find my practical experience has ever aligned with the idea that "comments aren't valuable". – Thomas W Feb 20 '22 at 05:26
  • For myself, I use a concise syntax expressing basically verb operations and concurrency over Entities selected declaratively. eg. `// notify Observers [LastUpdated <= EventTime]`. With bullet-points on subsequent lines to express contact & implementation semantics. – Thomas W Feb 20 '22 at 05:32
  • "commonly written as a bunch of undocumented and highly opaque mocking, state setup and assertions". Sure, but bad practices can be applied to anything, code, tests, even comments; I wouldn't avoid a good tool because some people abuse it. I was just suggesting that if you want to document the business purpose, and also have a sort of safety net when things change, that ATs would be a better tool than comments which can easily drift w/o notification to the dev. – user2051770 Mar 04 '22 at 14:43
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
  • 42,090
  • 4
  • 59
  • 119
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
  • 11,656
  • 4
  • 30
  • 41
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,549
  • 15
  • 23
  • 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
  • Your points on 3rd party libs and weird not-understood quirks of the code are EXACTLY the things I admit that you sometimes HAVE to comment, but that it should be viewed as an issue, a problem, a failure, something to avoid and something to fix, or to communicate via design instead. Do you really think this is an attitude that is actively harmful (I assume you're the one who downvoted)? – sara Apr 16 '16 at 12:50
  • I think the problem with that approach is it makes the assumption that the next developer will understand the reason you've done everything; what's obvious to you may not be obvious to the next person. I think it's better to pessimistically assume that your code does have issues, and that future developers will be confused by your code no matter how great your names are, or how clean/SOLID/DRY your code is. It only takes a minute to write a couple of short insightful comments; if that prevents a future developer making an "obvious" mistake, then it's a good time investment IMO. – Ben Cottrell Apr 16 '16 at 13:53