Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Sometimes I find myself in situations when the part of code that I am writing is (or seems to be) so self-evident that its name would be basically repeated as a comment:

class Example
{
    /// <summary>
    /// The location of the update.
    /// </summary>
    public Uri UpdateLocation { get; set; };
}

(C# example, but please refer to the question as language-agnostic).

A comment like that is useless; what am I doing wrong? Is it the choice of the name that is wrong? How could I comment parts like this better? Should I just skip the comment for things like this?

share|improve this question
7  
Note: I would consider "The location of the update" to be very vague unless it is crystal clear what "an update" is. Do the system support other kinds of URI's than URL's? –  user1249 Mar 29 '12 at 8:29
31  
return result # returns result –  Lukas Stejskal Mar 29 '12 at 10:55
25  
The way to deal with tautology in comments is the way to deal with tautology in comments. (This is a comment.) –  Rex Kerr Mar 29 '12 at 14:31
29  
This isn't really a comment, it's actually documentation written in the form of a comment. Different rules apply to API documentation than they do to inline code comments. –  Cody Gray Mar 29 '12 at 17:26
10  
This is simply an example of poor API Documentation, not code comments. My C# XML formatting for a property like this would look something like "Gets or Sets a Uri that can be used to access this object's update server." –  Kevin McCormick Mar 29 '12 at 18:37
show 15 more comments

17 Answers 17

up vote 12 down vote accepted

In most projects I work on, there isn't a significant amount of time to write detailed comments on every single class member.

That doesn't mean there isn't time for comments; on the contrary, there's plenty of time for tautological comments that puke back a rephrased version of whatever's being commented. They work great as a starting point.

Especially given Visual Studio's usage of comments accompanying IntelliSense, it's a good idea to start with a short bit of information about the field:

class Example
{
    /// <summary>
    /// The location of the update.
    /// </summary>
    public Uri UpdateLocation { get; set; };
}

And then as you continue to code, when you can't remember whether UpdateLocation was the location that the update took place, or the location that the update is being sent to, you'll have to revisit the code. It is at this point that you should add that additional information:

class Example
{
    /// <summary>
    /// The Uri location where the update took place.
    /// </summary>
    public Uri UpdateLocation { get; set; };
}

If ever another programmer asks you about details on a field, update the comments with that information:

What sort of update should Example.UpdateLocation be used to store?

class Example
{
    /// <summary>
    /// The Uri location where the Foo update took place.
    /// </summary>
    public Uri UpdateLocation { get; set; };
}

Just like a program has bugs, good comments have bugs that need to be iteratively worked out. The purpose of comments is to assist in understanding code when you revisit it six months later and can't remember anything about how the program works.

And just like programming, your comments have to start somewhere. Tautological comments are the Hello World! of comments, as you practice writing and updating documentation, your starting documentation will become more and more resilient.

share|improve this answer
1  
In my current project I've been hit more than I can count by the lack of comments on a large legacy code base. Something You as an author, think is blatantly self-explanatory method name for something You consider to be rather obvious functionality, might not be just as self-documenting in three months time to another developer. Documentation on methods, properties and fields should try to put a context to the wider picture and this answer explains the best process of reaching that goal, I've seen so far. –  Roland Tepp Apr 5 '12 at 12:38
show 3 more comments

Comments should never duplicate your code. Comments should not answer the "how?" question, but only "why?" and "what?". Why such an algorithm is chosen, what are the implicit assumptions here (unless your language is powerful enough to express it with type system, contracts and alike), what is a reason for doing this thing at all, etc.

I'd recommend to take a look at the Literate Programming practice for an inspiration.

share|improve this answer
4  
@stijn, I do not know - it is (obviously) missing from the code. Something that only the author of the code know about its purpose and limitations. –  SK-logic Mar 29 '12 at 9:23
15  
The most important question a comment should answer is "WTF?" –  naught101 Mar 29 '12 at 12:56
show 5 more comments

Comments should describe the code, not duplicate it. This header comment just duplicates. Leave it out.

share|improve this answer
16  
+1: I think I understand what you mean, but I don't agree with whay you said :-) As far as possible, code should describe code, whereas comments should describe your reasoning. –  Kramii Mar 29 '12 at 9:07
3  
@Kramii, unfortunately, code is incapable of describing the code, even if you're coding in Agda. No languages are as powerful and expressive as the natural language. And often you'll need plots, graphs, tables, complex formulas to describe the code - barely possible without a proper literate programming. –  SK-logic Mar 29 '12 at 9:18
6  
@SK-logic: I disagree. A long method is less self-describing than a short method that calls a series of well-named subroutines. –  Kramii Mar 29 '12 at 11:26
3  
@Kramii, sorry, I cannot see what you disagree with and how your comment is related to whay I've said. My point is that a lot of information should be provided alongside with your code which is totally missing from the code itself. All the history behind decisions you've made, all the relevant references to the papers, etc. - there are no language elements for expressing such things. And long vs. short methods/functions/subroutines/whatever is totally irrelevant here. –  SK-logic Mar 29 '12 at 12:39
2  
@SK-logic, what Kramii says means: "The code should be easy to read and understand itself" and all the graphs etc that you are mentioning falls into what he says as: "the comments should describe your reasoning" –  Shahbaz Mar 29 '12 at 15:43
show 7 more comments

Leave them out!

Normally, it is good practice to remove comments where the information expressed in them is already present elsewhere. If you can express the purpose of a method clearly and unambiguously by giving it a good name then there is no need for a comment.

Put them in!

Your example illustrates two exceptions to this rule:

First, "UpdateLocation" may (depending on context) be ambiguous. In that case, you either need to give it a better name or provide a comment to remove the ambiguity. Improving the name is generally the better option, but this is not always possible (when you are implementing a published API, for example).

Second, the "///" in C# indicates a comment that is intended to be used to auto-generate documentation. The IDE uses these comments to tool-tips, and there are tools (Sandcastle) that can generate help files and so forth from these comments. As such, there are arguments for inserting these comments even if the methods they document already have descriptive names. Even then, however, many experienced developers would frown on the duplication of information. The deciding factor should be the needs of those for whom the documentation is intended.

share|improve this answer
show 3 more comments

I strongly disagree with the "don't write comments" responses. Why? Let me point out by changing your example a bit.

public Uri UpdateLocation ();

So what does this function do:

  • Does it return the "update location"? or
  • Does it "update" the location and return the new location?

You can see that without a comment there is ambiguity. A newcommer can easily make the mistake.

In your example, it is a property so the "get/set" methods reveal that the second option is incorrect and it does indeed mean "update location" and not "update the location". But it is far too easy to make this mistake, especially in cases of ambiguous words such as "update". Play safe. Don't confuse someone new to this just for saving a few seconds of your time.

share|improve this answer
4  
I don't think anyone is advocating don't write any comments at all. Most/all are saying "write appropriate comments", which the UpdateLocation example would come under. –  Ozz Mar 29 '12 at 9:20
15  
Uri UpdateLocation() would be rejected by code review and changed to either Uri GetUpdateLocation() or to void UpdateLocation(). –  avakar Mar 29 '12 at 11:22
4  
@avakar: Agree with the sentiment, but as this is a C# property (get and set are automatically synthesised and have the same name) renaming to GetUpdateLocation would result in code like GetUpdateLocation = somelocation. LocationOfUpdate would be a better name, which removes the ambiguity. The basic problem is that the OP used a verb prefix instead of a noun. Leading verbs are presumed to indicate the action of a method. –  Ant Mar 29 '12 at 22:14
2  
@DPD, "How much time and effort does it take to wirt one line" how much effort does it take to maintain it? How much screen estate does it waste? How much time does it waste when it ultimately gets out of sync with the code and start to confuse developers? –  avakar Mar 30 '12 at 11:09
1  
The method returns a value, and has a verb-phrase name. This is the problem. It should have a noun-phrase name. e.g. 'Uri LocationOfUpdate()'. Not GetUpdateLocation, do you say “what is your GetLocation?”? –  richard Mar 30 '12 at 11:38
show 9 more comments

/// <summary> blocks are used for generating documentation for IntelliSense and API documentation.

Thus, if this is a public-facing API, you should always include at least a <summary> comment, even if the purpose of the function should be self-evident to readers.

However, this is the exception to the rule; in general, just remember to DRY (Don't Repeat Yourself).

share|improve this answer
add comment

Do fill comments like that only if you know how you'd benefit from stuff like that; otherwise just wipe them.

To me, case of clear benefit was when there was an automated check for missing comments and I was using that check to detect code where important information needed to be filled; for this I was indeed filling some placeholders - just to make sure that tool report does not contain "false alarms".

I think there is always a way to avoid blatant duplication. Over years I've come to using couple "template fillers" for cases like yours - mostly like self-descriptive name and see above.

For this particular example, I would use something of "self-descriptive kind" (assuming it's not the case where wiping out would do the job), like that:

class Example
{
    /// <summary>
    /// Self descriptive method name.
    /// </summary>
    public Uri UpdateLocation { get; set; };
}

Example when I could use see above kind fillers would be Javadoc comments that require dedicated fields for return value, parameters and exceptions. Quite frequently, I find that it makes better sense to describe most or even all these in single summary sentence, method that returns <describe what is returned> for provided parameters <describe parameters>. In cases like that, I fill in formally required fields with plain see above, pointing reader to summary description.

share|improve this answer
add comment

Here's a question I like to ask myself when thinking about whether to add a comment into a section of code: What can I convey that would help the next person understand the overall intent of the code better, so that they can update, fix, or extend it faster and more reliably?

Sometimes the correct answer to this question is that there is nothing much you can add at that point in the code, because you have already selected names and conventions that make the intent about as obvious as it can be. That means you've written solid self-documenting code, and that inserting a comment there would likely detract more than it would help. (Note that redundant comments can actually damage code reliability over time by slowing falling out of sync with the real code over time and thus making it harder to decipher the real intent.

However, in almost any program and in any programming language, you are going to encounter points where certain critical concepts and decisions made by the original programmer -- by you -- will no longer be apparent in the code. This is pretty much unavoidable because a good programmer always programs for the future -- that is, not just to make the program work once, but to make all of its many future fixes and versions and extensions and modifications and ports and who knows what to also work correctly. That latter set of goals is a lot harder, and requires a lot more thinking to do well. It is also very hard to express well in most computer languages, which are more focused on functionality -- that is, on saying what does this version of the program need to do, right now, in order to make it satisfactory.

Here's a simple example of what I mean. In most languages, a quick in-line search of a small data structure will have enough complexity that someone looking at it for the first time likely will not recognized immediately what it is. That's an opportunity for a good comment, because you can add something about the intent of your code that a later reader will likely appreciate immediately as helpful for deciphering the details.

Conversely, in languages such as the logic-based language Prolog, expressing the search of a small list can be so incredibly trivial and succinct that any comment you might add would just be noise. So, good commenting is necessarily context dependent. That includes factors such as the strengths of the language you are using and the overall program context.

The bottom line is this: Think to the future. Ask yourself what is important and obvious to you about how the program should be understood and modified in the future.[1]

For those parts of your code that are truly self documenting, comments just add noise and increase the coherency problem for future versions. So don't add them there.

But for those parts of your code where you made a critical decision from several options, or where the code itself is complex enough that its purpose is obscure, please, add your special knowledge in the form of a comment. A good comment in such a case is one that lets some future programmer know what must be kept the same -- that is the concept of an invariant assertion, incidentally -- and what is OK to change.


[1] This goes beyond the issue of comments, but it's worth bringing up: If you find that you have a very crisp idea of how your code could change in the future, you should likely think beyond just making a comment and embed those parameters within the code itself, since that will almost always be a more reliable way to ensure the reliability of future versions of your code than trying to use comments to steer some unknown future person in the right direction. At the same time you also want to avoid overgeneralizing, since humans are notoriously bad at predicting the future, and that includes the future of program changes. So, try to define and capture reasonable and well-proven dimensions of future at all levels of program design, but don't let it get you distracted into an exercise in excessive generalization that is unlikely to pay of in the long term.

share|improve this answer
add comment

Comments should be used to do one of the following.

  1. Information for document generators to grab. This can't be understated, this is extremely important.
  2. Warnings to why a piece of code is the way it is, and what other considerations. I've dealt with code written in 2 programming languages. One key part of this was to have a common structure between the two languages. A comment at both locations informing the user that if they change this number, they also need to change another is extremely helpful.
  3. Write notes to explain why a particularly weird looking piece of code is the way it is. If you had to think about how to get a piece of code to work in a particular way, and the solution isn't evident from the beginning, it's probably worth an explanation as to what you were trying to do.
  4. Labeling inputs/outputs, if they aren't clear. It's always good to know what your inputs are expected to be, and what format they are in.

Comments should not be used to do the following:

  1. Explain things that are extremely obvious. I once saw legacy code like this: page=0; // Sets the page to 0. I think any competent individual could figure that out.
share|improve this answer
add comment

I would remove the tautology but keep the comment, I would comment properties and variable names by giving a sample value, so that the usage is clearly understood:

property UpdateLocation:TUpdateLocation;  // url="http://x/y/3.2/upd.aspx",proto=http

Now I know exactly what goes in there, and from the comment, I have a clear idea how to use it.

share|improve this answer
add comment

In my own code, I will frequently leave comment tautologies in place, including the particularly egregious ones like:

<?php
// return the result
return $result;
?>

... which obviously contribute little in terms of making the code more comprehensible from an explanatory perspective.

In my mind, though, these comments still have value, if they help to maintain the visual consistency of the color patterns in your syntax highlighter.

I think of code as having a structure that is very similar to the English language, in that there are "sentences" and "paragraphs" (even though a "paragraph" may consist entirely of a single "sentence"). I usually include a line-break and one-line summary above each "paragraph". For example:

<?php
//get the id of the thing
$id = $_POST['id'];

//query the things out of the the database
$things = array();
$result = mysql_query("SELECT * FROM Things WHERE `id` = $id");
while ($row = mysql_fetch_assoc($result)) {
    //create a proper Thing object or whatever
    $things[] = new Thing($row);
}

//return the things
return $things;
?>

(Ignore the incomplete code, SQL injections, etc. You get the idea.)

To me, the final comment genuinely adds value to the code, simply because it helps to visually delineate one "paragraph" from another by maintaining a consistent coloring scheme.

share|improve this answer
show 3 more comments

I'd say it depends on the purpose of the comments.

If they're to be used to generate documentation for use by the team building it (or if they're just inline comments to explain things), then I think it's acceptable to leave that out. It can be safely assumed that it's self-explanatory; and when it's not, there are other team members nearby who can explain it. Of course, if it turns out it's not self-evident for a lot of people, you should add it in.

If the comments will generate documentation for some geographically distant team, then I would put every bit of documentation in there.

share|improve this answer
add comment

I think this topic has been discussed fairly extensively under names like "comments: anti-patterns", or "are comments a code smell?" (one example).

I tend to agree with the general idea that comments should add new information, not duplicate. By adding trivial comments like that, you are violating DRY, and decreasing the signal to noise ratio of the code. I tend to find high-level comments explaining the responsibilities, rationale behind, and example usage of the class much more useful than per-property comments (especially superfluous ones).

Personally, in your example, I would leave comment out (if there really is nothing useful to add about the property).

share|improve this answer
add comment

If you can write code that does not require comments then you have achieved programming nirvana!.

The less comments your code requires the better the code!

share|improve this answer
3  
This is not possible (and never will). There is always a lot of stuff left behind the code - implicit assumptions, architectural decisions, long chains of mathematical transforms ending up in a specific algorithm, etc. –  SK-logic Mar 29 '12 at 9:21
1  
Perhaps "Hello World!" is programmer nirvana then... –  naught101 Mar 29 '12 at 13:01
show 1 more comment

A comment like that is useless; what am I doing wrong?

It only seems useless if you already know what UpdateLocation does. Is "update" here a verb or a noun adjunct? That is, is this something that updates the location, or is it the location of the update? One might infer the latter from the fact that UpdateLocation is apparently a property, but the larger point is that sometimes it doesn't hurt to explicitly state something that seems obvious.

share|improve this answer
add comment

Auto-compiled documentation aside, code should document itself, so that comments should only document where the code is not enough to document itself.

share|improve this answer
add comment

"Location" is kind of obvious, but "Update" could be a bit vague. If you can't write a better name, then can you offer more detail in the comment? Update of what? Why do we need this? What are some assumptions (is null allowable)?

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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