Commenting in Java

J

js_dev

Java comments

Commenting in Java

Basics:
1) Javadoc comments are for permanent API documentation
2) Non-Javadoc comments are for the programmer to read and understand
things that are not so obvious from the code.
3) Professional programmers write flow commenting style (informal step
by step) for non-javadoc comments and also Javadoc style comments for
the API docs

Details:
1) Javadoc comments are a bit formal sounding, need to be factually
correct, and comprehensive of special cases. They are for long-term
reference of others.

2) Non- javadoc comments should preferably be informal, busy, and
light-sounding - preferably, only those things that are not obvious
from the code. At the beginning of a block of more than 50 lines, a
comment of size >= 5% of total code block(5 lines at least for 100
lines of meaningful code) is due if your code is to be called
well-commented. Better 10%. One comment every 10-15 meaningful lines
(not bracket-only lines and not System.out.println lines) is optimal
and good-looking. Note that the person reading your code should get
guidance in his thought process just as soon as he asks for it in his
mind or just before he needs it- if he gets the direction of the code
before reading the actual code, its fairly good commenting. Try to
guide your reader along. Use (a)tutor-like,
(b)trainer-like,(c)co-programmer-like language.

Use a conversational style.

3) Flow commenting means informal language and step by step treatment
of the logic.
It is a good idea to write all javadoc comments later, after coding and
testing and debugging, but it is imperative to write non-javadoc
comments while coding. Else, your commenting will not be high-quality
or sometimes will not even be accurate.

Read the article on Literate programming at Wikipedia
(http://en.wikipedia.org/wiki/Literate_programming)
and
this article on documentation
(http://en.wikipedia.org/wiki/Software_documentation)

In the ideal situation, your source code file should be the best manual
for another programmer. And the javadoc must look as good (or bad) as
Sun's JDK docs. User documentation is an altogether different ball
game. For that see the other blog.

Now, sometimes the code is so big or complicated that you simply cannot
put in comments and make the source file impossible to assimilate. Here
your code speaks for itself.

The following will be useful in such a scenario as also in general:
1) lucid, self-explanatory naming of variables e.g. txtTelNo or
cmbSpecialHolsList
2) good, consistent indentation (4 spaces/tab is accepted by all as
being easy on the eyes)

Some editors and IDEs (Notepad++ and Eclipse for instance) have
code-folding - they are lifesavers when it comes to files greater than
100 lines of code.

3) clean, simple programming - no complex for statements, multiple
initialisations, etc.

I insist that you do a google search for Good commenting practice and
good programming style.

In summary, you should know:

a) how to code in a flow-commenting style (conversational)
b) how to code with javadoc-comments
c) how to code without any comments at all
d) when to do which, out of (a), (b) and (c)

Happy commenting!

Must-see's:

http://filia.uni.lodz.pl/mocny/doc/j2sdk/docs/tooldocs/solaris/javadoc.html

http://java.sun.com/j2se/javadoc/writingdoccomments

http://barney.gonzaga.edu/java/tooldocs/javadoc/standard-doclet.html
 
P

Patricia Shanahan

3) Professional programmers write flow commenting style (informal step
by step) for non-javadoc comments and also Javadoc style comments for
the API docs

Sentences of the form "Professional programmers do X", other than the
tautology "Professional programmers are paid to program", are highly
suspect. I was a professional programmer for over 25 years. I have never
blindly added step by step comments to high level language code, nor
have I ever worked with coding standards that recommended doing so.
2) Non- javadoc comments should preferably be informal, busy, and
light-sounding - preferably, only those things that are not obvious
from the code. At the beginning of a block of more than 50 lines, a
comment of size >= 5% of total code block(5 lines at least for 100
lines of meaningful code) is due if your code is to be called
well-commented. Better 10%. One comment every 10-15 meaningful lines
(not bracket-only lines and not System.out.println lines) is optimal
and good-looking.

How did you determine optimality? Can you give a reference to the
relevant experiments?

I have a very different view of code comments:

Code comments have costs, breaking up the flow when reading and
reducing the amount of actual code that can be viewed simultaneously.
Deciding whether to write a comment involves a trade-off. Does the the
comment enhance the readability of the code by more than its cost?

Code can be so simple and obvious that no comment can enhance its
readability. It is not just "preferably, only those things that are
not obvious from the code.". If you don't have something non-obvious to
say, adding the comment adds cost without benefit, regardless of the
ratio of comment to non-comment lines.

On the other hand, consider a short block of code that represents a
non-obvious algorithm. A well-written comment may add substantially to
its readability, even if the comment is longer than the code.

Incidentally, a 100 line block of code in Java is unusual, and might be
a candidate for refactoring.
It is a good idea to write all javadoc comments later, after coding and
testing and debugging,
....

Why? I usually write the javadoc comment for a method as soon as I
think the method is going to exist, before I even have its unit test,
let alone any code. If I don't know enough to write the javadoc comment,
I don't know enough to write the unit test, or any other calls to the
method, or the method's own implementation. If I do know enough to write
the javadoc comment, I might as well write it, eliminating any potential
confusion about exactly what the method is supposed to do.

===========================================================

I have a question about your whole series of posts. You seem to be
posting numerous large, apparently random, blocks of advice, much of it
controversial, with little or no explanation of why you think the advice
is any good.

Why? What's the objective?

Patricia
 
R

Roedy Green

If I do know enough to write
the javadoc comment, I might as well write it, eliminating any potential
confusion about exactly what the method is supposed to do.

I am more of Patricia's comment first school too. Get very clear on
just what the method will and will not do before you write it. That
will save you from the temptation of inserting bits of housekeeping
where they don't logically belong but have to go somewhere.

For me, figuring a good name for the method and parameters is half the
battle. You want something unambiguous that makes clear what method
does and does not do. You have to think, what functions might someone
plausibly imagine this method would do, then clarify most by the name,
and the rest by comments.

Eclipse, with its global rename is great. It lets me easily rename if
I later think of a better name or some new method introduces an
ambiguity.

It is a way of being polite to yourself. When you come back cold to
code later, if you have been careful in naming, it all makes sense
again very quickly.

The docs you need most coming back cold are the BIG picture. Details
you can easily glean from code. It is amazing how quickly you forget
the overall structure -- the stuff "too obvious" to document.

Also too, I find lack of big picture docs are always the problem in
making sense of someone else's code.
 
J

js_dev

First and foremost, if there is a comp.lang.java.beginner forum, i am
unaware of it, kindly let me know how to get in there and i'll stop
posting here - as it is I am reconsidering - its good when you are
viewed by the best in the business, you realize you must post only the
best!

A very simple purpose - to help beginners like me a couple of months
back - I found answers to many questions here, so I decided to pay back
a bit

IM very HO,
1)often simple things are not easily found to beginners - they are lost
quite often
- this "experiment" gets conducted almost every week by hundreds of
programmers and a beginner searches a lot and gets confused to get just
a few working lines of code up and running (you are not a beginner
_clearly_ ) - mosrt of my other posts were meant to put up those few
lines.

2)detailed, correct and professional methodologies are not best for
beginners' study
- that is accepted by industry as true - you can't learn everything at
once, can you?

3) Finally, I (and _everyone_ _else_ who follows these trails) got a
real lot of good information from the replies that all of you posted -
if you could also mention url's to relevant articles on good
programming practice, it will be a still better help to everyone.

NOT to say that I am going to employ such a practice - of inciting
comments by "controversial" posts - I am least interested in such
activities.

Regards,
Joseph S.
 
R

Raymond DeCampo

First and foremost, if there is a comp.lang.java.beginner forum, i am
unaware of it, kindly let me know how to get in there and i'll stop
posting here - as it is I am reconsidering - its good when you are
viewed by the best in the business, you realize you must post only the
best!

A very simple purpose - to help beginners like me a couple of months
back - I found answers to many questions here, so I decided to pay back
a bit

IMHO, this is better accomplished by
1) creating a web site that contains your advice
2) answering specific questions as they arise, perhaps including
links to your web site

Keep in mind that despite Google's archive, most news servers do not
keep posts indefinitely. So random informative posts like yours need to
be re-posted at intervals. It makes most sense to keep it on a web site.

Kudos on your desire to give back to the community.

HTH,
Ray
 
P

Patricia Shanahan

2)detailed, correct and professional methodologies are not best for
beginners' study
- that is accepted by industry as true - you can't learn everything at
once, can you?
....

No, you can't learn everything at once, but it is good to learn a subset
of best practices, so that you never have to unlearn bad habits. Start
with the subset you need for one class projects...

I'd suggest at this stage distinguishing two types of information:

1. Hard facts, such as "java.util.Arrays contains a series of sort methods".

If you find any statement of hard fact in a reasonably high Page-ranked
web page, it is probably reasonably accurate. Moreover, you should be
able to evaluate the accuracy of these statements by experimentation and
reading API documentation. I stick to this type of issue when posting on
a topic for which I'm a beginner.

2. Style and technique issues, such as commenting rules.

There are numerous opinions on these issues. They are argued over by
experts. Web searches will find many opinions, and without deep
programming experience it is hard to sort out which ones represent
alternative views of good practices, and which are just plain wrong.

It is best not to post definite "do it this way" instructions on these
issues, unless you are aware of the alternatives, have compared them,
and can explain why the way you are advocating is definitely right.

I'm still curious about the reasons for your views on Java code
commenting. Why step by step? Why a target percentage of comment lines?
Why leave javadoc to the end? I've given my views on these issues, and
reasons for those views, but I'm always open to being convinced
differently by good enough arguments.

Patricia
 
M

Mike Schilling

1) Javadoc comments are a bit formal sounding, need to be factually
correct, and comprehensive of special cases. They are for long-term
reference of others.

All comments had better be factually correct, unless your only goal is job
security.
 
R

Roedy Green

All comments had better be factually correct, unless your only goal is job
security.

“Incorrect documentation is often worse than no documentation.”
~ Bertrand Meyer
 
E

Eric Sosman

Roedy said:
“Incorrect documentation is often worse than no documentation.”
~ Bertrand Meyer

Years ago I read (perhaps in Weinberg's "The Psychology
of Computer Programming") of an experiment in which computer
science students were assigned chunks of "real" code to
debug. Half the group received the original code, the others
got the same code samples but with all the comments removed.
The latter group found more bugs and found them faster than
those who had the "benefit" of the comments. I surmise that
a sufficiently persuasive comment can lure the reader into the
same flawed line of reasoning that suckered the original author.

My favorite comment of all time was found by a colleague
debugging someone else's C code:

#define HASHSIZE 51 /* a small prime */
 
V

Virgil Green

Eric said:
Years ago I read (perhaps in Weinberg's "The Psychology
of Computer Programming") of an experiment in which computer
science students were assigned chunks of "real" code to
debug. Half the group received the original code, the others
got the same code samples but with all the comments removed.
The latter group found more bugs and found them faster than
those who had the "benefit" of the comments. I surmise that
a sufficiently persuasive comment can lure the reader into the
same flawed line of reasoning that suckered the original author.

My favorite comment of all time was found by a colleague
debugging someone else's C code:

#define HASHSIZE 51 /* a small prime */

Oddly, I find this to be one of my favorite numbers... precisely because it
is small, looks at first glance as though it would be prime, but most
definitely is not.
 
M

Mike Schilling

Virgil Green said:
Oddly, I find this to be one of my favorite numbers... precisely because
it
is small, looks at first glance as though it would be prime, but most
definitely is not.

5 + 1 = 6, so it's clearly divisible by 3.

91, on the other hand, looks prime (and isn't).
 
C

Chris Uppal

Eric said:
My favorite comment of all time was found by a colleague
debugging someone else's C code:

#define HASHSIZE 51 /* a small prime */

;-)


But....

Did the software depend in any way of the prime-ness of HASHSIZE ? If so, was
that obvious from the code alone (and not via an additional step: "Ah I
recognise this as <such-and-such> algorithm, and I happen to know that only
works well with primes") ? If not, then how would you have known that the
author had made a mistake ?

I can tell the story of a similar mistake that I once made, that (had it not
been caught by an eagle-eyed college -- who /read/ the comments and compared
them with the code) might have had Very Serious Consequences for the company I
worked for.

Redundancy is good. The /reason/ it's good is that errors can be detected, and
ambiguities resolved. In
the case of comments, that means that the possibility of divergence between
code and comment is (one of the many) /advantages/ of commenting, not a
disadvantage.

-- chris
 
A

Andrea Desole

Chris said:
But....

Did the software depend in any way of the prime-ness of HASHSIZE ? If so, was
that obvious from the code alone (and not via an additional step: "Ah I
recognise this as <such-and-such> algorithm, and I happen to know that only
works well with primes") ? If not, then how would you have known that the
author had made a mistake ?

I can tell the story of a similar mistake that I once made, that (had it not
been caught by an eagle-eyed college -- who /read/ the comments and compared
them with the code) might have had Very Serious Consequences for the company I
worked for.

Redundancy is good. The /reason/ it's good is that errors can be detected, and
ambiguities resolved. In
the case of comments, that means that the possibility of divergence between
code and comment is (one of the many) /advantages/ of commenting, not a
disadvantage.

Redundancy is good when comments are correct. But if comments are wrong
you might waste a lot of time trying to find out how the code can do
what is told in the comment, when it's actually doing something
different, For example, the author might have wanted, at the beginning,
to use a prime number. After that he changed his mind, but not his
comment. This makes you think "why did he put this comment? 51 is not
prime. And why would I need a prime anyway?" (by the way, why do I need
a prime? Is it related to the hash size?). Of course, you also think
"maybe the comment is wrong", but you just spend more time checking and
rechecking that you understand the code correctly, and that the comment
is wrong. Not to mention, of course, the case when you trust a wrong
comment.
Now, don't misunderstand me, I like comments, and documentation. But
comments do have a drawback. Comments are good, too many comments
sometimes are not.
 
C

Chris Uppal

Andrea said:
Redundancy is good when comments are correct. But if comments are wrong
you might waste a lot of time trying to find out how the code can do
what is told in the comment, when it's actually doing something
different

Agreed, but you seem to be assuming that the comments are going to be wrong
(significantly) more often than the code. IMO, this is only true of
incompetent programmers (as a matter of definition, rather than an observed
correlation).

With redundancy, you know that something is wrong (but not what). Without
redundancy then there is no hint that anything is wrong. Which would you
prefer ? If the divergence is due to mistakes in the code in a large fraction
of cases, then that warning flag is valuable. (Of course, if the mistake /is/
usually in the comment, then that doesn't hold).

(But, yes, I do agree that some comments are worthless -- often as a result of
coding standards that require a specific content and layout of (say) method
comments. Such rules tend (in my experience) to result in comments that are at
best vacuous, and when not vacuous, just plain wrong. But that's a problem
with the red-tape and/or company culture, not a reason to avoid writing -- or
reading -- comments.)

-- chris
 
B

bugbear

Roedy said:
For me, figuring a good name for the method and parameters is half the
battle.

Amen, brother!

For internal clairity, you could add local variable names
to that list.

Names that accurately (and compactly, but that's *hard*)
express semantics can be extraordinarily helpful.

BugBear
 
V

Virgil Green

Mike said:
5 + 1 = 6, so it's clearly divisible by 3.

True... but most people I know don't know about the sum-of-digits rule for
multiples of 3.
91, on the other hand, looks prime (and isn't).

Agreed... it's another interesting number.

Call me odd, but I just fine particular beauty in certain numbers. 169 and
196 come to mind. I like them because they are perfect squares of
consecutive integers and have their last two digits switched. When playing
tennis, I find some elegance in the 15-40 or 40-15 score. I don't know why
on that one -- it just is the most appealing to me of the available
combinations.
 
M

Mike Schilling

Chris Uppal said:
Redundancy is good. The /reason/ it's good is that errors can be
detected, and
ambiguities resolved.

Yes, yes, yes. People who judge programming languages by how few keystrokes
each requires miss this. The "every string means *something*"-ness of C is
one of its biggest drawbacks.
 
M

Mike Schilling

Call me odd, but I just fine particular beauty in certain numbers. 169 and
196 come to mind. I like them because they are perfect squares of
consecutive integers and have their last two digits switched. When playing
tennis, I find some elegance in the 15-40 or 40-15 score. I don't know why
on that one -- it just is the most appealing to me of the available
combinations.

You might like this story:

http://www.anecdotage.com/index.php?aid=4038
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,740
Latest member
AdolphBig6

Latest Threads

Top