Coding Without Comments

Disclaimer: I’m probably still considered Junior level at this point

Either way, I’ve seen both extreme ends of code lacking sufficient documentation, and code which has excessive documentation that doesn’t add anything to it.

  1. Obviously, it is a mistake to comment every single line of code you write. This has been my annoyance in a lot of code that I’ve inherited from previous employees. For example:

/* if local preferences is null /
if (LocalPreferences == null)
/
return /
return;
/
if dynamic report is not null /
if (DynamicReportPanel != null)
{
DynamicReportPanel.SetPreferences ();
} /
if DynamicReportPanel != null */

this is a real section of code I’m maintaining… If your comment does not say anything more than the line of code itself would say if read out loud, then please don’t waste the time to say it (and my time in reading it)… I have had to go to the extreme and remove all comments from certain sections of code… and it actually did help readability…

  1. The other extreme of not writing comments period, is just as bad. Consider the situation as well that I have inherited code written by a senior developer which is comment-less. The methods all have very logical, explanatory names, but when it gets down to the details of what’s going on, I’m left to read through and figure out what all of the rest is doing. Plainly and simply put, if you’re coding in a work environment, odds are that someone else is going to have to do bug fixes or other maintenance to the code that you wrote. Stepping into a piece of code, a developer won’t necessarily understand how your classes are structured, or even necessarily how your methods are put together.

  2. I think the biggest problem I’ve been seeing with comments is the granularity of detail that they seek to explain. 99% of the time, you shouldn’t have to explain a single line of code, and if you do, you should probably see if there’s a more straightforward way to write it (in the examples, i do agree that some formulas are a pretty good candidate for the exception to the rule).

Sparse block comments can really help establish the functionality of a section of code without having to read and understand every single line detail of the process, giving a brief logical overview to someone who has never touched your code before, and as such, can become a sort of map for navigating to applicable sections of code, or to get one’s bearing within a particular segment. One of the comment-less pieces of code i received parses through a pretty complex tree without any note on what we’re looking for at any particular level.

IMHO, if you need to comment individual lines, try refactoring, but don’t neglect to give a generalized roadmap of what a particular chunk of code is supposed to accomplish…

I am writing thousands lines of code and they should be all mess without comments. Sure, I agree that code should be written as clear as assumed to be without comments but comments must exists.

In my opinion, readibility of code is one of the major problems and comments are part of code. It is ‘in line documentation’.

It is not necessary to comment all lines, but programmer should write what (s)he intended by writing code blocks, I prefer to write comments on:

  • Function / Subroutine headers about parameters and what this function does
  • Long or cascaded If blocks
  • Select - Case structures
  • Global variables
  • Name of common mathematical theorems or calculation methods

If you want to produce long living software, you should never omit writing necessary comments. I have seen several project that rewritten because of too complex structure without comments. We have redesigned and rewrite all codes from scractch instead of upgrading it because upgrading was nearly impossible, it was easier to rewrite it again.

Hi!

From my point of view there is nothing wrong with commenting your classes, methods, etc.

At least working with VS.Net it will help to use XML comments for creating a documentation in an automated way (included within a automated build process).

But I agree that there is no need to write prosa about how your code works - that should be self explaining. And using sensefull naming helps, aswell.

I published the definitive treatment of comments in 1989:-)
A short letter: don’t say that i++ adds 1 to i, but to
state what must true (but is not obvious) at that point of a program.

In the case in the article add these before the function
//Do not call if n0
//Global t must be 0
//returns r with abs(sqrt(n)-r) …
(if you can fill in this blank then you don’t need the comment).

RJB

All of this is good discussion. It is why I enjoy the Coding Horror blog. Although I have programmed for 20 years, I have learnt much from reading responses of my fellow programmers.

Of course, everything is context. So there is not strictly one way to write comments. Sometimes we think all other programmers are in same situation as we are, with same skills, experience, and same manner of doing things. Much of reason for writing the comment is to help OTHER programmer figure out how the code was intended to work. Of course, 12 months from now, I might as well be the OTHER, when I am trying to maintain old program I have written long ago.

When I write code, I ask myself: if I or someone else must revise or debug the code 12 months from now, how quickly will the programmer be able to figure out what the code is trying to do? And is there chance that programmer (I or someone else) will leap to wrong assumptions and introduce new bugs when trying to make revisions to old code? Will less experienced programmer be able to quickly understand and make additions to code without wrecking it?

First I write the code to make as much sense all on its own. Then I make sure the comments fill in the important detail for the later programmer. It is important to keeping it brief and clean and keeping comments up to date, as old comments that no longer apply may confuse the later programmer. Write comments in the language of later programmer, if you know who will be maintaining the code.

Sometimes I might even write the less efficient but more maintainable code. I do this if I know that the code will more likely to be updated later, and performance is not the primary issue. As I said, everything is context. It depends on thinking through life of the code after I have done with it and making best decisions accordingly.

I have no comment

Good variable/method/class naming is essential in making the code understandable. On the other hand there are many situations when you cannot express everything important without a full paragraph. I don’t like to see 80 character method names. In my opinion 1-2-3 carefully picked short words should be enough. In time the assumptions, constraints and requirements at the time of writing become very important and they might not be obvious later during maintenance.
If anybody is interested I elaborated more on how bad comments are born in the code at http://littletutorials.com/2008/07/30/how-bad-comments-are-born-in-your-code/

Dude, I really don’t know your background, but to say something like Junior developers rely on comments to tell the story when they should be relying on the code to tell the story. you’re just perpetuating myths.

Right now I have a project that is structured like crap, no comments, but everything is well named. Trying to figure out what the original programmer wanted to do versus what it is doing is nearly impossible. A few comments with regards to the intentions of a block of code would be nice. Things fail and you’re never sure if it is OK that the code is ignoring that failure, or that is the cause of the whole problem.

comments is good then it’s right comment in right place of code,

more else good make the objects that contains not only properties and methods but and can give information about their properties and methods

I agree that comments need to be used in moderation. Personally, I feel that the biggest difficulty with writing too many comments is keeping them up-to-date as you refactor your code. Maybe it’s just me, but I usually forget to update them.

If you try to write clear and understandable code, I think that’s the most important thing.

I long for the day when my problem is that there are too many comments in other people’s code.

Problem with your fix is that you should really put some form of comment on the function, what it’s for, when to use it, why, and what n is.

I agree with a lot what’s being said here.
I am for code being self commenting, like using good names for the function. It doesn’t matter about length of names now as the IDE makes it easier now.

Comments don’t get updated as much as code. I’ve seen this and the result is that the comments LIE about what the code is doing!

Functions should be named and refactored so that they are doing one thing, then the code is usually small enough to just read and know.

It’s always good to see comments as to why the code was wrote a certain way though if that code has some not so obvious design decisions.

But I’m sure I’m like most of you here, having to dig through legacy code with bad programming, no comments, no nice names (clickety_click being the best example recntly) and having to spend a long time just trying to figure out whats going on just to make a small change.

Jeff, commenting on a highly subjective area like comments shows exactly why reading personal blogs are waste of time sometimes. Your posts worth while when you raise a question for discussion or stating statistical facts but posts like these waste people’s time when you try to tell them how there is only one way to present comments with one example.

someone’s going to shoot me if they ever have to maintain a module I wrote.

It implements a thread-safe hashtable that requires no locks on read. At the top if insert2 is a comment along the lines of

'We have the lock, now insert the record w/o disturbing things)

and at the critical moment

'Understand this line or don’t touch this code.

The marked line is a no-op looking function call that prevents the optimizer from rearranging the code into a non-thread-safe version.

Tell that to my Java professor! He’s enforcing comments every 5 lines no matter how inane. So not only do I have to suffer through Java, but also worry about losing points for not commenting enough.

//This line adds 2 and 6, producing 8
int t = 2 + 6

It’s a damn shame

Jeff,

I think you're opinion is really great and provides some valid points.  I consider my code to be rather clean but I still make sure to usually have about 1 line of comments right before a block of code to help when I have to go back and support/update it.

My view is that comments are like a conversation with yourself reminding you of what the hell you were thinking.

A few things come to mind when reading this article.

  1. Always comment a procedure or method. Say what it does, just a line or two. Come on, how hard can it be?

  2. Comment any gotcha’s (e.g you must do x before doing y) or non-obvious assumptions (although assert is good for this).

  3. A comment every 15 lines or so helps new readers navigate through the code. After all, you would find it hard to drive on unfamiliar roads without signposts, wouldn’t you?

  4. When pointers are passed in and out of functions, make it clear who owns them when the function returns, e.g.:

    // Caller must free pointer returned
    char *get_a_string ()

Having said all of which, I don’t put that many comments in my code. Instead, I try to make the code easy to read by using sensible names and good layout.

Just my $0.02 worth. Happy coding.

Paul Sanders
http://www.alpinesoft.co.uk

I don’t really agree with what you are saying.

Comments in code are a real soap box for me; probably because I have wasted countless hours working through other people’s code that is badly formatted and contains very few, if any, comments. I always try to comment my code well, and it annoys me greatly when other people don’t.

  • Re Comments should describe the why rather than the what
    I agree with this up to a point, but if (say) I have a loop in my code which counts some stuff, I don’t see a problem with putting a comment at the start of the loop such as Count some stuff. Yes, you can work out what it’s doing by looking at the code, but the comemnt saves time examining the loop itself to see what it’s doing, only to forget again for the next time I look at it! the idea that code is self commenting is a complete nonsense put about by lazy people who just can’t be bothered to do a decent job.

  • A problem just as bad as poorly commented code, is badly formatted code. take your example…

Here’s another fun one I found yesterday.

/** Timeout for response in ms */
public static final int DEFAULT_TIMEOUT = 40000; // This is arbitrary, no reason I chose this
...
synchronized (sem)
{
   try
   {
       log(Waiting for response);
       sem.wait(DEFAULT_TIMEOUT);
   } catch (InterruptedException e)
   {
       log(Caught InterruptedException waiting for response: %s, e);
   }
}