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.

This question already has an answer here:

A friend told me that writing comments inside methods is not good. He said that we should have comments only for the method definitions(javadocs) but not inside the method body. It seems he read in a book that having comments inside the code means there is a problem in the code. I don't quite understand his reasoning. I think writing comments inside the method body is good and it helps other developers to understand it better and faster. Please provide your comments.

share

migrated from stackoverflow.com Feb 28 '11 at 10:33

This question came from our site for professional and enthusiast programmers.

marked as duplicate by gnat, BЈовић, MichaelT, Dan Pichelman, Dynamic Jun 16 '13 at 14:21

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

10  
Removed the "java" tag because I think this question's interesting to anyone using any language, even if they don't have inline documentation. –  Rei Miyasaka Feb 28 '11 at 2:23
3  
If there was a java-tag, it was a useful information, since the tool javadoc uses comments above the method, but not comments inside the method. –  user unknown Feb 28 '11 at 5:51
7  
Sounds like he's read Clean Code but only parts of it :-). –  Oliver Weiler Feb 28 '11 at 9:04
1  
Tell your friend about the en.wikipedia.org/wiki/Literate_programming –  SK-logic Feb 28 '11 at 11:22

24 Answers 24

Your friend is wrong, and very few programmers would agree with him. You should write comments whenever and wherever you feel they best aid understanding.

share
4  
Your words means nothing, you say whenever and wherever aid, but the problem is what codes need aid, the codes need aid is just the problem. –  guilin 桂林 Feb 28 '11 at 8:09
3  
@guilin: That's only true for very simple problems... –  nikie Feb 28 '11 at 11:16
7  
True, however the other end of the spectrum indicates your code should be self-documenting and simple enough to understand at a glance. One could argue that, if inline comments are needed, your code is too complex or not self-documenting. But it largely depends on the application - I'd hate to see inline comments in a row of statements like /* do this and that */ doThis(); doThat();, but they'd be very much in place in a method that does numerous not-too-obvious calculations. –  Cthulhu Feb 28 '11 at 11:30
3  
@Cthulhu: I think everybody agrees that there are bad inline comments. (Probably too many.) The question was if there's such a thing as a good inline comment. –  nikie Feb 28 '11 at 12:58
21  
Inline comments are often needed to document "odd" code or algorithms that are working around bugs, problems, or poor design in other libraries. There is no way to make these "self documenting" and they are often inappropriate for the method comments. –  James Schek Feb 28 '11 at 15:08

Ignore your friend. Comment as needed. But endeavor to make your code self-explanatory, so that comments aren't needed. Remember that your computer isn't executing comments, and so it's easy for comments to get out of sync with what's actually going on.

I tend to use a block of comment to explain a particularly tricky bit of logic, that would otherwise take some brain-twisting to read. And then I'll try to make the logic more clear, and remove the need for explanation.

share
6  
+1 for self-explanatory –  Hoàng Long Feb 28 '11 at 2:11
4  
+1 for comments getting out of sync! –  Trufa Feb 28 '11 at 11:09
3  
+1 for endeavoring to make comments unnecessary, but using them where they are needed. That's probably the best summary I have seen so far! –  Michael Kjörling Feb 28 '11 at 15:23

Good code is self-documenting. A method should do exactly one thing, and that one thing should be obvious by the method name and comment specs. Therefore, needing comments in the method explaining the logic suggests that the method should be broken up into single responsibility methods.

Now, for reality. You're faced with a complex spaghetti-code codebase and you're trying to be nice to the maintainers. You don't have the time or mandate to refactor 8 million lines of code, and even if you did, there would be nuances because everything is complex. What do you do?

share
7  
Downvoters comment please and thank you. –  Mark Peters Feb 28 '11 at 1:26
1  
I like this post (+1) -- but think that it (the first bit anyway) excludes any comment whereas the post describes a novel of comments, for which I think there is a big difference. –  pst Feb 28 '11 at 2:56
14  
There is no such a thing as "self-documenting code" (no, I'm not a downvoter). Comments are all about "why?", and the code is about "how?". –  SK-logic Feb 28 '11 at 10:38
1  
Au contraire, I have read a lot of code that I would describe as self-documenting. A good example would be the Delphi Visual Component Library. That code base is a work of art. With that said, most of the Java code that I have read is not even close to being classified as self-documenting. –  bit-twiddler Feb 28 '11 at 19:24

I am surprised how many people disagree with this view.

  1. Good code should be self-documenting, so you should carefully choose methodnames, variable names, etc
  2. Your method should not be so long that you cannot see the whole method and the comments in one screen

That said, there are exceptions. But they are exceptions. And the point with is exceptions, is that they are few in numbers. You really only need to explain code inline if you're doing something counterintuitive.

A typical situation where you might need comments in your method is when you apply a local hack to optimize for speed, but which on first reading might give another programmer a wtf moment. That's a good point to add an comment.

But in general: no, do not add comments in your methods.

share
5  
@Marten But you wouldn't need the comment if you put 2 into a variable describing what 2 means, like private static final int MAX_SOMETHING = 2. With a proper IDE this takes a fraction of a second. –  Oliver Weiler Feb 28 '11 at 9:07
3  
I do a lot of financials programming, and as a result, a lot of my methods are just math equations. Every single one of those needs to be exhaustively commented. –  Satanicpuppy Feb 28 '11 at 19:21

I think he is talking about a case like this:

public void upload() {
    // destination host
    String host = ....
}

Where you could make the code better by having a more explicit variable name, rather than the comment:

public void upload() {
    String destinationHost = ....
}
share

I believe your friend is referring to "Clean Code" by Robert C. Martin. However, I think he is oversimplifying the situation a bit. The book talks about giving methods clear and descriptive names, which we should all know, but which can never be repeated enough. The book also recommends making methods very small by wrapping any block of code that can be given a clear and descriptive name into a method of its own. So if you feel that a block of code needs a comment explaining what it does, then you should make it a separate method with an appropriate name. In theory, if all your methods are under 5 lines, and if they all have good descriptive names, it should be obvious what they do without having to explain it in a comment.

However, it does not mean that you should never have comments inside your methods. The point is that comments should not be redundant. They should add information. If you have a method that does exactly one thing, and that thing is obvious from its name, then you do not need a comment explaining what it does. However, it makes perfect sense to have a comment explaining why it does its thing in that particular way. You may want a comment explaining why you chose one algorithm over another, or why you chose one data structure over another. In other words, you want the code itself to explain how it works, and you want the comments to explain the reasons for your design decisions, i. e. why things are done this particular way.

The book recommends refactoring bad code instead of commenting it. This is certainly a great idea in theory, but in reality you may not have the time or the infrastructure, such as a working unit test framework with the appropriate set of unit tests to do that. There are times when you are faced with a messy code base, which you need to get working yesterday, and the only way to move forward is to try to understand the messy pieces, and to comment them as a way to make notes for yourself.

share

Yes, you definitely write comments inside methods in Java.

As Sun's code convention says:

Java programs can have two kinds of comments: implementation comments and documentation comments. Implementation comments are those found in C++, which are delimited by /*...*/, and //. Documentation comments (known as "doc comments") are Java-only, and are delimited by /**...*/. Doc comments can be extracted to HTML files using the javadoc tool.

So, the comments in methods are implementation comments.

share

I strongly disagree with your friend and contend that inline function comments are a very important part of writing good code. Function comments are designed to give clients of the code a better understanding of what the code is supposed to do - what its parameters and return values mean, the sorts of invariants it expects to have on entry and exit, etc. Inline comments, however, are directed primarily at maintainers of the code and ideally as a series of mental notes for the original author of the code. They make it possible to look at a complex method that another person has read and to intuit what the original author was thinking. They also make it easier to diagnose bugs, since if the comments describe what the intention of the code is and what assumptions it's making, it can be much easier to figure out how a piece of code is erroneous when a malfunction is detected.

I personally find inline comments useful because they force me to prove to myself that the code I'm about to write is going to work correctly. Often, I'll make a habit not to write any code without first clearly commenting what the intention is and how it's going to work. More times than not, this prevents me from making silly mistakes in the code because I'll find that my explanation is incorrect or doesn't take some edge case into account.

Of course, everyone has their own coding discipline, and perhaps some people find it easier to write code without inline comments and to instead split the code up into multiple smaller methods. However, from experience I've found that inline commenting is invaluable during development and debugging, and extremely useful for other people who have to look over and maintain my code long after I've moved on to another project.

share

Your friend may well be expressing the notion that comments are, if not themselves a "code smell", a "deodorant". This isn't specific to in-method comments, but it may tend to be truer of in-method comments than of preamble comments.

When you write a comment, typically it is to explain something. When something needs explaining - well, it's not self-explanatory. Great code is self-explanatory. So when you add comments, you're covering up its failure to self-explain, without making it self-explanatory. So every time you write a comment like that, instead of changing the code - by renaming, by method extraction, etc. - to make it self-explanatory, you're falling short of the ideal.

But we all fall short of perfection now and again. And it's often better to add an explanatory comment than to leave hard-to-understand code undocumented.

share
2  
+1 for addressing it as a code smell/deodorant. –  Levinaris Feb 28 '11 at 18:36

When commenting your code (or the really badly documented code of someone else) you may often be confronted with feelings of sheer disgust, hate or wrath. The code may behave in frustrating and unexpected ways and you may have to add some very evil hacks to make it work for some deadline.

In all those cases expressing your feelings by annotating the respective portions of code with some heavy swearwords (see the linux kernel fuckcount) is common practice. Those comments must live inside the methods so they do not appear in the auto-documented API, so neither your boss nor your clients nor any other sourcecode agnostic person will ever see it.

Your fellow programmers however will feel great relief and happiness when studying the source. (And of course you can add notes to yourself, or use the source code as a communication medium to some extent, #TODO: add more examples here)

Of course you might argue, that these kinds of comments are not supposed to be there in the first place, or that they should be removed before the final release, but these days software projects have very short release cycles, and some comments are still relevant many nightly builds later, so maybe your friend should start learning to read (and write) between the lines.

share

Good comments explain the why not the how. That is the key distinction here. Most people will be able to follow what you are doing but why you did it requires extra comments. Those comments should be close to the operation as possible.

share

It is common practice for programmers to put comment inside methods whenever they think it is not clear for other programmers what the code is doing. Also Programmers put TODO comments inside the method sometimes. However, it is true that if you have too much comments inside methods, you might need to step back and think if you are doing things too complicated than it should be. In other word, you probably want to avoid to comment about something obvious for other programmers as it is harder to read the code with them.

To take your friends suggestion positively, you should remember that we can avoid commenting too much by naming variables and methods properly and keep each method small and make sure they don't do too much staff.

share

I think the reason he said that is because he believes functions should be short enough that each one encapsulates only a single conceptual operation.

I don't necessarily subscribe to that belief to its extreme (for various reasons, including that reading such code can become a nightmare), but if one did, it might follow that they'd only have one comment per function, as there's only one concept per function and one comment per concept.

Either way I use comments whenever and wherever there's code whose choice or behavior isn't immediately obvious -- often having to do with performance considerations or esoteric math. That sort of stuff often doesn't immediately concern the function's consumer, so I'd argue that it's in fact a good idea to hide it from the documentation.

share

I believe your friend was talking about javadoc, which will generate documentation from your comment if it is above your method declaration (and decorated with an extra asterisk) like this:

/**
   get a webpage for a given url 
   @param url: the url to get
   @returns String: the http-source 
*/
public String getWebpage (String url) {
... 

If you put this comment inside the method it is useless.

Therefore - as a rule of thumb: put comments in java source above the method.

Exceptions may and will occur. I agree to: use short methods, write self-documenting code. However javadoc as a tool encourages duplication of comments, because else it looks so naked in the documentation. :)

share

I concede the point that in a method written from scratch, one could document it's function within the header only. However.

I find that comments are often inserted where bugs were discovered and a subtle nuance was overlooked even if the method only has a single responsibility -- which let's be honest, is rarely the case in legacy code. Further, I see no reason to have a variable name that's forty characters long (even if it's only used in two places) when a shorter variable name with a succinct comment can be more easily digested and reused later. Clean and concise is best, but above all, it's a means of communication to other programmers as much as emails, letters, and poetry are as well. And to that I add the quote:

“I have only made this letter longer because I have not had the time to make it shorter.”

Blaise Pascal, (1623-1662) Lettres provinciales

share

It's nice to have code that doesn't need commenting. When you get, save, and delete things, we have a pretty good idea what's going on and don't need comments.

Sometimes the code gets messy and is a candidate for refactoring, so you may have to comment in the mean time.

Today I had a line of code not do what is expected. Apparently a .net datatable doesn't think a row that was imported is a new record. When you insert the records from the table nothing happens. The row being imported has to have it's status changed first. A simple comment is all that is needed, so when I come back to it 6 months from now and think, "What the hell do I need that for?" I'll know.

share

Comments only make the code more programmer friendly, remember comments are not going to be executed.

If you were to read your code after few months, the comments will make reading through the code easier.

It will make the code maintainable and any other programmer who looks at the code will find it easy to understand the logic you have implemented.

It does not mean that you have to always add comments even for a method with few lines of code.

Like for example the following code is self explanatory and does not require any comments to make its function clear

public String getName(){
    return name;
}

While when a method is large do add comment so that it is more readable whenever any programmer looks at it.

Remember while coding you might think that the code is self explanatory, but when you may look at it after six months the comments you added six months ago will definitely help you or any other programmer understand the code quickly.

share

Firstly, your question was specifically Java-oriented--which significantly influences the answer.

The amount of commenting that is required is highly related to the language which you are working in.

  • Some languages such as Java and C# lend themselves extremely well to the concept of self-documenting code. In these languages your efforts are best-spent making the code itself as readable and descriptive as possible, and then adding in-line comments only for things which you can't describe natively within the language.

  • Some languages such as SQL are more difficult to make readable. The syntax, order of evaluation, nesting, and so on can make it more challenging to design in a self-documenting manner. The same basic approach still applies: focus on using the language as much as possible, then add comments to compensate for areas that are unclear or confusing.

Overall you cannot 100% abolish comments, but your goal should be to remove the need for comments as much as possible by making the code more self-describing. The results of these efforts are usually less code overall and better organized code. Regardless of whether or not there are still comments present this means that your code will be much more maintainable and approachable--which is really what comments are intended to aide with in any regard.

share

The idea that Javadoc (or even Delphi autocomplete hints) should change the way a person codes (other than to add functionality for javadoc) is pretty absurd.

Ask your friend which came first, the javac or javadoc?

That's like asking which came first, the cow or Mrs. O'Leary


Also, javadoc should be for people implementing your class and functions, the comments in the code are for the people who are maintaining your code. Especially with your private methods, no one should necessarily have to look at your code to see what it does. That's what the doc's are for. But if someone needs to tweak something because of a hairy off by one error, then you want to comment that up in your method.

He's obviously assuming the 90% of code which is in fact bug fixes are all bad. I've never read "The pragmatic programmer" but I can assume he's not referencing that book.

share

Your friend is wrong.
Your friend is partially correct in that the USER of your method should only need to read the documentation comments. However, unless you are writing unambiguous, clear clean code that will NEVER need to be modified for any reason whatsoever (This means requirements and platforms will never change) then comments in the body are very helpful.

When I am writing code with unclear design (This does happen, it shouldn't but it does.) I will often write the documentation comments (what the method should do), the method block (Return 0, return null, throw NotImplemented -- Whatever you need) and then write implementation comments such as:

//Get Connection String
//Connect to DB !!-- EXCEPTION --!!
//Build Query and Params.
//Parse Query Results
//Return answer

This will give a clear idea to me what needs to be done. It will also give a future developer a clear idea as to what I was trying to accomplish.

In other words, Documentation comments are for users, explaining WHAT is being done. Internal Comments (Code Comments) are for developers, explaining HOW it is being done.

share

Great question.

The answer might be "it depends."

If you can break out an unclear portion into a method or function of its own, please do so, and others who must maintain your code will arise and call you blessed. Use Javadoc comments to make the unclear more clear. This may be your friend's main point.

Here is a quote from a comp sci text whom I cannot remember (and apologies to the author):

i++; // increment the counter

The author's point in the example is that the comment is superfluous. If you have taken Programming 101, you don't need the comment.

If you are doing something not-blazingly-obvious to others (or possibly yourself six weeks from now), then by all means comment the not-so-blazingly obvious.

For example, do you immediately comprehend

assertFalse("valid status differs", file1.isValid() ^ file2.isValid);

or might you be helped by these comments

// Java XOR operator a^b returns true iff a and b differ.
// If file1 and file2 are both isValid, return false.
// The assertion is that the two versions of isValid should be the same.

Even if you're superb with boolean operators and use XOR regularly, the comments should help and speed your comprehension.

Or consider this fragment to convert a string to an int, using a Number n, without comments:

...
} else {
  Double d = (Double) n;
  Long l = d.longValue(n); 
  int ans = n.intValue(); 
  if (l.equals ((long) ans)) return ans; 
  throw new ParseException("Field too big to be stored as int");
}

Compare to commented code:

...
} else {
  // n must be a double
  Double d = (Double) n;
  Long l = d.longValue(n); // l contains the sInt as a long
  int ans = n.intValue(); // was it truncated?
  if (l.equals ((long) ans)) return ans; // not truncated -- they were equal as longs
  throw new ParseException("Field too big to be stored as int");
}

I will readily admit that this last fragment is "heavily commented." I think good programmers will code to help communicate and clarify. Err on the side of liberal comments. You can always remove them later.

share

I will toss my two cents now that the party is pretty well over. I use comments when I'm describing a specific bit of business logic or when I have to add something to cover an unforseen edge-case.

Code evolves over time to account for things which weren't known beforehand, and so when you apply a band-aid, instead of assuming that it's known why you put that band-aid on, it sometimes helps to add a little block within the code that says "oh, by the way, I had to fix this and here's the bugtracker reference so you can follow the surrounding conversation" and in my case (as I use FogBugz) it would look like this:

//Case: 1234 ~ Throttling based on unusual activity per ABC request.
Throttler myThrottler = new Throttler( oldActivity );

or whatever. So my point is that something that seems out of place and isn't as readable is probably a good place to inline document. Collected knowledge is a beautiful thing.

But my first point was my business logic. I literally have a block in a stored procedure that I'm about to rewrite this AM that has some business rules in the front.

/****************************************************************
author  yourstruly
date    2010-11-18
descrip intended use is to blah blah blah
        ended up over actual measured blah blah blah according to blah blah blah
        rules from the customer are:
        If the sum of the blah blah blah is higher than the blah blah blah
        and the blah blah blah contain blah blah blah,
        and the blah blah blah is non-zero,
        recalculate the blah blah blah to fit within the blah blah blah

        Additional rules for us internally: 
        if the blah blah blah originally read blah blah blah don't blah blah blah (set to zero)

        rewritten here with (1) traceable statements for the where clauses.
        If 
            the blah blah blah(1) is higher than the blah blah blah (2)
        and the blah blah blah (3)
        and the blah blah blah is non-zero (9)
        and the blah blah blah is lower than the blah blah blah (4)
        and the edited blah blah blah is higher than the blah blah blah (5)
        then recalculate the blah blah blah (6)
        // See note lower in this document on the math

        If 
            the blah blah blah(1) is higher than the blah blah blah (2)
        and the blah blah blah (3)
        and the blah blah blah is higher than the blah blah blah (7)
        then set the blah blah blah to zero (8)

        (7) dictates the same as (4) but it's easier to do (7)
****************************************************************/

Sorry for the blah blah blah's but proprietary rules and all that ;)

And all of a sudden you see that I have requirements(!) embedded in my code as comments and I can refer to the comments as /*(1)*/ (which I do) so that this is easily traceable for the next employee (which it was, and he was able to find the parts that needed tweaking immediately) and then if anyone wants to know what the spec was they can read the commentary from above, and if anyone wants to know what the pseudo-code is it's there and if anyone wants to convert the pseudo-code to the code then there you go. To me this is much more readable (for my case) as it preserves the original request (snipped from the email) and allows the train of thought to be quickly gathered in without too much thought, and allows for the use of easy transformations of the pseudo into real code.

And yes, there are some inline comments saying that such and such didn't work as expected in the pseudo-code because the requirement didn't quite match the data so we needed to tweak the data. But that's my point. We documented in-line the edge cases, and we left the pseudo-code in the code proper to follow the logic, so we all knew what was expected from the original requirements

share

The problem with inline comments is that they have to be maintained along with the code (also true for function/method/module/class-level comments, but not to as great a degree); God knows how much source code is still out there where the comments have absolutely nothing to do with the code they document anymore, which IMO is just as bad or worse than not having any comments at all.

Ideally, inline documentation should be limited to the following situations:

  • Explaining code that's heavily optimized or "tricky", along with a justification for why the code is so heavily optimized or "tricky" ("we were missing performance requirement X and profiling showed the bottleneck to be in this section; the optimizations below gained Y% performance");

  • Referring to a standard or requirement ("DTED 0 post spacing is 30 arc seconds");

  • Identify code that needs further analysis/development ("TODO");

First law of code docmentation - don't document the obvious. Corollary to the first law of code documentation - write code that's obvious to the greatest extent possible.

share

Comment when it is necessary, not as much as possible.

share

This site is currently not accepting new answers.