Are there standard formats for comments within code? [closed] - comments

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'm wondering if people have a standard format for comments in their code. Not things like xml comments for a method or class but rather comments within a method.
See also:
Is there a standard (like phpdoc or python’s docstring) for commenting C# code?

You should really consider a couple things to make good comments beyond formatting.
Do not simply restate what the code is doing. For example,
// Start the services
StartServices();
is a frigging terrible comment!
Describe why. Why is the code doing what it's doing? What's the business assumption or algorithm step?
Format your comments for maximum readability. Tab them properly, leave spaces where necessary, etc.
If someone has already started commenting in a standard way, don't break that standard.
Check this article on MSDN about writing effective comments: http://msdn.microsoft.com/en-us/library/aa164797.aspx

// I usually write comments like this
Where I work it is required to use standard xml comment style for most of the declarations (classes, methods, some properties) (we use C#).
Sometimes you can see header/footer comments in use.
/****************************************************/
// Filename: Customer.cpp
// Created: John Doe
// Change history:
// 18.12.2008 / John Doe
// 14.01.2009 / Sara Smith
/****************************************************/
/* Here goes a lot of stuff */
/****************************************************/
// EOF: Customer.cpp
/****************************************************/
Something like this was used at one of my old places of work. In my opinion too much of unnecessary stuff. Change history is nicely seen these days through a version control system.
In many good software shops there are internal guidelines as to when and how to write comments. Documents are typically referred to as "Source code style policy" or something. It is very important to adhere to one common style in commenting the code.
Of course this commenting hype shouldn't go too far as to comment every little piece of code, especially the obvious ones.
/// <summary>
/// Handles the standard PageLoad event
/// </summary>
/// <param name="sender">
/// Event sender
/// </param>
/// <param name="e">
/// Event arguments
/// </param>
public void Page_Load (object sender, EventArgs e)
{
// Do something here
}
This one is a good example of over-obsession with commenting. Something like this adds exactly zero information but only adds noise to the source file. And we have to do it at work as required.
My personal opinion is add comments when you have something to say or explain, not just for the sake of commenting everything.

/**
* block comments to document a method for javadoc go like this
* #param
* #return
* #exception BTKException
* #see BTK
*/

Comment on the line above the code (block) that does what you're describing
// This is a comment.
Some code goes here
Avoid doing stuff like
// ----------------
// IMPORTANT COMMENT
// ----------------
And I avoid using the
/* comment */
And perhaps most importantly, clean up comments! A comment that describes non-existent functionality is worse than no comment at all.

//For one line, I write them like this
/*
For multiple lines of text
I write them like this
*/
/*
for(multiple lines of code){
I.WriteComents(With("//"));
Reason==If(I.Remove('The top begin-quote mark') then
I.Worry.Not('About removing the close-quote mark');
//*/

The problem with comments within a method (rather than in an interface), is that they are actually not meant to be seen by anyone except for people maintaining that method. Therefore, there is no real need for a standard for the comments. They don't get published anywhere, they're not publicly visible, callers will generally never see them.
In general, comments inside code should follow four rules:
They should not state the obvious
They should be consistent with what they describe
It should be clear what they describe (e.g., which line, block).
They should be readable by any future maintainer.
That being said, there is often a tendency to place information that is important to the callers as an internal comment. For example: "OOPS, This doesn't handle negative numbers". Whenever you see an internal comment, reconsider whether the header documentation should be updated, or use a tool that "pushes" the comments to the awareness of function callers (I have a tool like that for Java).

/* I will sometimes write
comments like this */

I can't believe we missed the REM keyword.
Though to be fair, it's for REMARK not COMMENT.

# ----------------------------------
# BIG IMPORTANT COMMENTS IN PERL/SH
# ----------------------------------

Comments standards are most useful when the comment will be parsed by an external tool (usualy, a document generator, like javadoc).
In this case, the external tool will state the standards.
For other cases, see How do you like your comments? (Best Practices)

//Cheap Debugger
//Response.Write(MySQLStringBecauseINeedToKnowWhatsBroken);

' I usually write comments like this

<!--How about comments like this!?-->

There are packages that will help write and format documentation. They require some specific changes so they can identify classes of comments.
such as doxygen:
http://www.doxygen.nl/manual/docblocks.html
/*! \brief Brief description.
* Brief description continued.
*
* Detailed description starts here.
*/

(* Modula-2 comments go like this *)

If you are paranoid and don't use or trust source control, you might do this
// Initials-YYMMDD-fixNo-Start
dosomething();
// Initials-YYMMDD-fixNo-Finish
It makes a bloody big mess, but it gives you some way to rollback changes.
But I'd suggest using source control

There can be religious wars on this subject.
What I try to do, that doesn't cause too much warfare, is
// explain the purpose of the following statement in functional terms
... some statement ...
The idea is, if I run the code through a program that deletes everything except the comments, what is left is pretty good pseudocode.
Something that's useful as a way to comment out code that you think you might need again is:
/*
... some code ...
/**/
then modify the first line - either delete it, or change it to /**/
/**/
... some code ...
/**/

/*
* Brief summary of what's going on.
*/
int code_that_goes_on(int c)
{
/* and then if I have to remark on something inside... */
return 0;
}
99% of compilers will support // comments, which is awesome, but that 1% still exists, and it's not too difficult to make life livable for them.
EDIT: The Delphi comment is a bit obtuse, but does point out a real deficiency. I intend this to be a C-specific answer.

I don't think there is a standard for what you are asking. And I don't see how it would add any benefit from /// comments on the method itself.
For creating documentation from your C# classes take a look at Sandcastle.

In C/C++/C#/Java, when I have a comment explaining a block of code:
// comment
code;
more_code;
when a comment is explaining a single line:
code; // comment
I usually use // for single sentence comments and /* ... */ comments for multi-sentence comments.

One comment style in C++/Java etc is this:
// Use // for all normal comments...
// and use multiline comments to comment out blocks of code while debugging:
/*
for(int i = 0; i < n; ++i) {
// If we only use // style comments in here,
// no comment here will mess up the block comment.
}
*/
I think it is an interesting point, even if it's not that incredibly useful.

My code is self-documenting. I need no comments.

I'm surprised that not more people recommended doxygen. It is a good way of documenting code, with the side effect that it can automagically generate html + pdf API documentation at the end of the day.

I prefer commenting this way for function
/**
* Activates user if not already activated
* #param POST string verificationCode
* #param POST string key
* #return true on success, false on failure
* #author RN Kushwaha <rn.kuswaha#gmail.com>
* #since v1.0 <date: 10th June 2015>
*/
public function activateUserAccount() {
//some code here
}
I use single line comment for code descriptions like
//check if verificationCode exists in any row of user table
code here

You might want to at least consider using standard comment formats for the PHP Reflection Class: https://www.php.net/manual/en/reflectionclass.getdoccomment.php
My sites compress html so a comment like
// comment here
in JS will crash the java script.
The specs for using // in PHP is only supposed to be a "short comment" ie: one line. Personally I don't think they should be used for more than one line.
Using them also makes it impossible to compress - or a lot harder to compress than what it should be.
Lastly.
Human interpretation is NOT absolute - a computer code is :)
So if you have a code that needs to or should be read - (Go Nasty) and don't comment it. ie: Force the reader to read the code rather than you relying on their interpretation of your comment.

Related

How can I add "comments" that don't become part of the code base?

Often when I am learning a new technology, I like to add verbose comments everywhere, so that if I come back and am confused about something, I can refer back to the comments. However, sometimes comments and certain frameworks (ahem React) don't mix well.
I'm looking for, perhaps an extension of some sort, that will allow me to place comments in Visual Studio that will never get placed in the actual source code. Something a la commenting in Excel.
I think that is a kind of complicated to find, an easy alternative that you can try are the #regions on C# to hide/ show your comments:
#region comments
/**
* Some comments here
*/
#endregion
public void myMethod(){
//TODO
}

New to Java - general JavaDoc issues

General JavaDoc questions here:
How do I know if they are working? I know the format and what they're supposed to be doing, but how do I know if they're doing their job? Should it print out after compiling and running?
Another question - how many JavaDoc comments do I need? My professor really wants us to examine our methods in these commentaries, and explain any variables. Does that mean put it inside the method? or before the method but inside the class? or before the class?
Thanks for any help!
I think you may be a tad bit confused as to what JavaDoc actually does.
JavaDoc does not directly impact your program in anyway. JavaDoc is a means of compiling information about your program. Say you get a program and want documentation of what it does in a nice handy format. Common compilers like eclipse have an option to compile an html file full of documentation, just like it shows on the Java API documentation. https://docs.oracle.com/javase/7/docs/api/
This is all JavaDoc for the most part, it is generated from comments.
My teachers always tell me in regards to comments, you are not commenting for someone who doesn't read code. You don't need comments like....
// Prints out hello world
System.out.println("hello world");
A programmer knows this functionality already. Programmers are more interested in parameter names and what functions actually do. Example
/**
* #param a Number we are dividing into
* #param b Number we are dividing by
* #return Our quotient
*/
public static float divide(int a, int b) {
return (a/b); }
Will generate a page like this
Emphasis on the /** at the top, two asterisks denote that below contains JavaDoc. Most IDE's like Eclipse will highlight JavaDoc.
As you can see the names of the parameters are just a and b, in certain cases it is difficult to label parameter names by what their function may be, so it can save time to use JavaDoc to give a description of them, instead of someone scrolling through your code trying to figure out what the hell they do. You are creating a guide for your program to modify and update it.
JavaDoc is literally a guide to how all your functions, classes, variables work in your program.

Sectioning off code with comment blocks for readability. Good or bad idea?

So I recently started programming and sometimes I feel to need to separate my code with comment blocks like this:
//===============================================================================
//Constructors
//===============================================================================
*constructors*
//===============================================================================
//End of Constructors
//===============================================================================
For example, I might have a "Constructor" section and a "Getter/Setter" section, or a "Ok Button Implementation" section with all of OK Button's configuration, click listeners etc. This allows me to quickly scroll through a giant list of code but still be able to quickly tell that "this entire block of code are constructors" without actually looking at the code/comments of each method.
I know there is also code folding which I actually use in conjunction with comment blocks (I surround the comment blocks with a custom folding region). The reason I do that is because Code Folding is great when all code is folded, but when code is expanded, they don't stand out like a giant comment block can. So I use one to cover the case when all my code is minimized and the other to cover the case when all my code is expanded.
However, this is not a practice that I see used much so I am wondering if it is considered bad coding practice or something. I mean, this definitely helps the readability of my code to ME, but I also wouldn't want prospective employers to dock points for a weird coding style.
There is always a practice being used in coding languages like for JAVA you may see as follows:
/**
Author : Gary
Method : testMethod
Parameters : param1, param2
Exception : ArrayOutOfBound, Exception
Description : It is a dummy method
*/
public void dummyMethod(int param1, double param2) {
//Sample Method Body;
String abc = callDummyMethod();
}
You can add on your part to the existing practice to enhance it even more for yourself, and it shall also be the ease to other programmers if you find need for your code to be reviewed/debugged by them.
PS: Single Line comments(//) are never encouraged in this form.

What are your "hard rules" about commenting your code? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 months ago.
Improve this question
I have seen the other questions but I am still not satisfied with the way this subject is covered.
I would like to extract a distiled list of things to check on comments at a code inspection.
I am sure people will say things that will just cancel each other. But hey, maybe we can build a list for each camp. For those who don't comment at all the list will just be very short :)
I have one simple rule about commenting: Your code should tell the story of what you are doing; your comments should tell the story of why you are doing it.
This way, I make sure that whoever inherits my code will be able to understand the intent behind the code.
I comment public or protected functions with meta-comments, and usually hit the private functions if I remember.
I comment why any sufficiently complex code block exists (judgment call). The why is the important part.
I comment if I write code that I think is not optimal but I leave it in because I cannot figure out a smarter way or I know I will be refactoring later.
I comment to remind myself or others of missing functionality or upcoming requirements code not present in the code (TODO, etc).
I comment to explain complex business rules related to a class or chunk of code. I have been known to write several paragraphs to make sure the next guy/gal knows why I wrote a hundred line class.
If a comment is out of date (does not match the code), delete it or update it. Never leave an inaccurate comment in place.
Documentation is like sex; when it's
good, it's very, very good, and when
it's bad, it's better than nothing
Write readable code that is self-explanatory as much as possible. Add comments whenever you have to write code that is too complex to understand at a glance. Also add comments to describe the business purpose behind code that you write, to make it easier to maintain/refactor it in the future.
The comments you write can be revealing about the quality of your code. Countless times I've removed comments in my code to replace them with better, clearer code. For this I follow a couple of anti-commenting rules:
If your comment merely explains a line of code, you should either let that line of code speak for itself or split it up into simpler components.
If your comment explains a block of code within a function, you should probably be explaining a new function instead.
Those are really the same rule repeated for two different contexts.
The other, more normal rules I follow are:
When using a dynamically-typed language, document the expectations that important functions make about their arguments, as well as the expectations callers can make about the return values. Important functions are those that will ever have non-local callers.
When your logic is dictated by the behavior of another component, it's good to document what your understanding and expectations of that component are.
When implementing an RFC or other protocol specification, comment state machines / event handlers / etc with the section of the spec they correspond to. Make sure to list the version or date of the spec, in case it is revised later.
I usually comment a method before I write it. I'll write a line or two of comments for each step I need to take within the function, and then I write the code between the comments. When I'm done, the code is already commented.
The great part about that is that it's commented before I write the code, so there are not unreasonable assumptions about previous knowledge in the comments; I, myself, knew nothing about my code when I wrote them. This means that they tend to be easy to understand, as they should be.
There are no hard rules - hard rules lead to dogma and people generally follow dogma when they're not smart enough to think for themselves.
The guidelines I follow:
1/ Comments tell what is being done, code tells how it's being done - don't duplicate your effort.
2/ Comments should refer to blocks of code, not each line. That includes comments that explain whole files, whole functions or just a complicated snippet of code.
3/ If I think I'd come back in a year and not understand the code/comment combination then my comments aren't good enough yet.
A great rule for comments: if you're reading through code trying to figure something out, and a comment somewhere would have given you the answer, put it there when you know the answer.
Only spend that time investigating once.
Eventually you will know as you write the places that you need to leave guidance, and the places that are sufficiently obvious to stand alone. Until then, you'll spend time trawling through your code trying to figure out why you did something :)
I document every class, every function, every variable within a class. Simple DocBlocks are the way forward.
I'll generally write these docblocks more for automated API documentation than anything else...
For example, the first section of one of my PHP classes
/**
* Class to clean variables
*
* #package Majyk
* #author Martin Meredith <martin#sourceguru.net>
* #licence GPL (v2 or later)
* #copyright Copyright (c) 2008 Martin Meredith <martin#sourceguru.net>
* #version 0.1
*/
class Majyk_Filter
{
/**
* Class Constants for Cleaning Types
*/
const Integer = 1;
const PositiveInteger = 2;
const String = 3;
const NoHTML = 4;
const DBEscapeString = 5;
const NotNegativeInteger = 6;
/**
* Do the cleaning
*
* #param integer Type of Cleaning (as defined by constants)
* #param mixed Value to be cleaned
*
* #return mixed Cleaned Variable
*
*/
But then, I'll also sometimes document significant code (from my init.php
// Register the Auto-Loader
spl_autoload_register("majyk_autoload");
// Add an Exception Handler.
set_exception_handler(array('Majyk_ExceptionHandler', 'handle_exception'));
// Turn Errors into Exceptions
set_error_handler(array('Majyk_ExceptionHandler', 'error_to_exception'), E_ALL);
// Add the generic Auto-Loader to the auto-loader stack
spl_autoload_register("spl_autoload");
And, if it's not self explanatory why something does something in a certain way, I'll comment that
The only guaranteed place I leave comments: TODO sections. The best place to keep track of things that need reworking is right there in the code.
I create a comment block at the beginning of my code, listing the purpose of the program, the date it was created, any license/copyright info (like GPL), and the version history.
I often comment my imports if it's not obvious why they are being imported, especially if the overall program doesn't appear to need the imports.
I add a docstring to each class, method, or function, describing what the purpose of that block is and any additional information I think is necessary.
I usually have a demarcation line for sections that are related, e.g. widget creation, variables, etc. Since I use SPE for my programming environment, it automatically highlights these sections, making navigation easier.
I add TODO comments as reminders while I'm coding. It's a good way to remind myself to refactor the code once it's verified to work correctly.
Finally, I comment individual lines that may need some clarification or otherwise need some metadata for myself in the future or other programmers.
Personally, I hate looking at code and trying to figure out what it's supposed to do. If someone could just write a simple sentence to explain it, life is easier. Self-documenting code is a misnomer, in my book.
I focus on the why. Because the what is often easy readable.
TODO's are also great, they save a lot of time.
And i document interfaces (for example file formats).
A really important thing to check for when you are checking header documentation (or whatever you call the block preceding the method declaration) is that directives and caveats are easy to spot.
Directives are any "do" or "don't do" instructions that affect the client: don't call from the UI thread, don't use in performance critical code, call X before Y, release return value after use, etc.
Caveats are anything that could be a nasty surprise: remaining action items, known assumptions and limitations, etc.
When you focus on a method that you are writing and inspecting, you'll see everything. When a programmer is using your method and thirty others in an hour, you can't count on a thorough read. I can send you research data on that if you're interested.
Pre-ambles only; state a class's Single Responsibility, any notes or comments, and change log. As for methods, if any method needs substantial commenting, it is time to refactor.
When you're writing comments, stop, reflect and ask yourself if you can change the code so that the comments aren't needed. Could you change some variable, class or method names to make things clearer? Would some asserts or other error checks codify your intentions or expectations? Could you split some long sections of code into clearly named methods or functions? Comments are often a reflection of our inability to write (a-hem, code) clearly. It's not always easy to write clearly with computer languages but take some time to try... because code never lies.
P.S. The fact that you use quotes around "hard rules" is telling. Rules that aren't enforced aren't "hard rules" and the only rules that are enforced are in code.
I add 1 comment to a block of code that summarizes what I am doing. This helps people who are looking for specific functionality or section of code.
I comment any complex algorithm, or process, that can't be figured out at first glance.
I sign my code.
In my opinion, TODO/TBD/FIXME etc. are ok to have in code which is currently being worked on, but when you see code which hasn't been touched in 5 years and is full of them, you realize that it's a pretty lousy way of making sure that things get fixed. In short, TODO notes in comments tend to stay there. Better to use a bugtracker if you have things which need to be fixed at some point.
Hudson (CI server) has a great plugin which scans for TODOs and notes how many there are in your code. You can even set thresholds causing the build to be classified as unstable if there are too many of them.
My favorite rule-of-thumb regarding comments is: if the code and the comments disagree, then both are likely incorrect
We wrote an article on comments (actually, I've done several) here:
http://agileinaflash.blogspot.com/2009/04/rules-for-commenting.html
It's really simple: Comments are written to tell you what the code cannot.
This results in a simple process:
- Write any comment you want at first.
- Improve the code so that the comment becomes redundant
- Delete the now-redundant comment.
- Only commit code that has no redundant comments
I'm writing a Medium article in which I will present this rule: when you commit changes to a repository, each comment must be one of these three types:
A license header at the top
A documentation comment (e.g., Javadoc), or
A TODO comment.
The last type should not be permanent. Either the thing gets done and the TODO comment is deleted, or we decide the task is not necessary and the TODO comment gets deleted.

What's the least useful comment you've ever seen? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
We all know that commenting our code is an important part of coding style for making our code understandable to the next person who comes along, or even ourselves in 6 months or so.
However, sometimes a comment just doesn't cut the mustard. I'm not talking about obvious jokes or vented frustraton, I'm talking about comments that appear to be making an attempt at explanation, but do it so poorly they might as well not be there. Comments that are too short, are too cryptic, or are just plain wrong.
As a cautonary tale, could you share something you've seen that was really just that bad, and if it's not obvious, show the code it was referring to and point out what's wrong with it? What should have gone in there instead?
See also:
When NOT to comment your code
How do you like your comments? (Best Practices)
What is the best comment in source code you have ever encountered?
Just the typical Comp Sci 101 type comments:
$i = 0; //set i to 0
$i++; //use sneaky trick to add 1 to i!
if ($i==$j) { // I made sure to use == rather than = here to avoid a bug
That sort of thing.
Unfilled javadoc boilerplate comments are particularly useless. They consume a lot of screen real estate without contributing anything useful. And the worst part is that where one such comment appears, hundreds of others are surely lurking behind.
/**
* Method declaration
*
*
* #param table
* #param row
*
* #throws SQLException
*/
void addTransactionDelete(Table table, Object row[]) throws SQLException {
I've found myself writing this little gem before:
//#TODO: Rewrite this, it sucks. Seriously.
Usually it's a good sign that I've reached the end of my coding session for the night.
// remember to comment code
wtf? :D
Something like this:
// This method takes two integer values and adds them together via the built-in
// .NET functionality. It would be possible to code the arithmetic function
// by hand, but since .NET provides it, that would be a waste of time
private int Add(int i, int j) // i is the first value, j is the second value
{
// add the numbers together using the .NET "+" operator
int z = i + j;
// return the value to the calling function
// return z;
// this code was updated to simplify the return statement, eliminating the need
// for a separate variable.
// this statement performs the add functionality using the + operator on the two
// parameter values, and then returns the result to the calling function
return i + j;
}
And so on.
Every comment that just repeats what the code says is useless. Comments should not tell me what the code does. If I don't know the programming language well enough, to understand what's going on by just reading the code, I should not be reading that code at all. Comments like
// Increase i by one
i++;
are completely useless. I see that i is increased by one, that is what the code says, I don't need a comment for that! Comments should be used to explain why something is done (in case it is far from being obvious) or why something is done that way and not any other way (so I can understand certain design decisions another programmer made that are by far not obvious at once). Further comments are useful to explain tricky code, where it is absolutely not possible to determine what's going on by having a quick look at the code (e.g. there are tricky algorithms to count the number of bits set in a number; if you don't know what this code does, you have no chance of guessing what goes on there).
Thread.Sleep(1000); // this will fix .NET's crappy threading implementation
I once worked on a project with a strange C compiler. It gave an error on a valid piece of code unless a comment was inserted between two statements. So I changed the comment to:
// Do not remove this comment else compilation will fail.
And it worked great.
I don't believe it. I came into this question after it had 22 answers, and no one pointed out the least possibly useful type of comment:
comments that are wrong.
It's bad enough that people write superfluous comments that get in the way of understanding code, but when someone writes a detailed comment explaining how something works, and it's either wrong in the first place, or wrong after the code was changed without changing the comment (much more likely scenario), that is definitely the worst kind of comment.
GhostDoc comes up with some pretty interesting ones on its own.
/// <summary>
/// Toes the foo.
/// </summary>
/// <returns></returns>
public Foo ToFoo()
// secret sauce
// Don't know why we have to do this
try
{
...some code...
}
catch
{
// Just don't crash, it wasn't that important anyway.
}
*sigh
Came across a file once. Thousands of lines of code, most of it quite horrendous. Badly named variables, tricky conditionals on loops and one comment buried in the middle of the file.
/* Hmmm. A bit tricky. */
//' OOOO oooo that smell!! Can't you smell that smell!??!??!!!!11!??/!!!!!1!!!!!!1
If Not Me.CurrentMenuItem.Parent Is Nothing Then
For Each childMenuItem As MenuItem In aMenuItem.Children
do something
Next
If Not Me.CurrentMenuItem.Parent.Parent Is Nothing Then
//'item is at least a grand child
For Each childMenuItem As MenuItem In aMenuItem.Children
For Each grandchildMenuItem As MenuItem In childMenuItem.Children
do something
Next
Next
If Not Me.CurrentMenuItem.Parent.Parent.Parent Is Nothing Then
//'item is at least a grand grand child
For Each childMenuItem As MenuItem In aMenuItem.Children
For Each grandchildMenuItem As MenuItem In childMenuItem.Children
For Each grandgrandchildMenuItem As MenuItem In grandchildMenuItem.Children
do something
Next
Next
Next
End If
End If
End If
Default comments inserted by IDEs.
The last project I worked on which used WebSphere Application Developer had plenty of maintenance developers and contractors who didn't seem to be bothered by the hundreds, if not thousands of Java classes which contained the likes of this:
/**
* #author SomeUserWhoShouldKnowBetter
*
* To change this generated comment edit the template variable "typecomment":
* Window>Preferences>Java>Templates.
* To enable and disable the creation of type comments go to
* Window>Preferences>Java>Code Generation.
*/
There was always that split-second between thinking you'd actually found a well-commented source file and realising that, yup, it's another default comment, which forced you to use SWEAR_WORD_OF_CHOICE.
I saw this comment yesterday in a C# app:
//TODO: Remove this comment.
My favorite all-time comment.
/* our second do loop */
do {
Whoever wrote it - you know who you are.
a very large database engine project in C many many years ago - thousands of lines of code with short and misspelled variable names, and no comments... until way deep in nested if-conditions several thousands of lines into the module the following comment appeared:
//if you get here then you really f**ked
by that time, i think we knew that already!
In a huge VB5 application
dim J
J = 0 'magic
J = J 'more magic
for J=1 to 100
...do stuff...
The reference is obviously THIS ... and yes, the application without those two lines fails at runtime with an unknown error code. We still don't know why.
Taken from one of my blog posts:
In the process of cleaning up some of the source code for one of the projects I manage, I came across the following comments:
/*
MAB 08-05-2004: Who wrote this routine? When did they do it? Who should
I call if I have questions about it? It's worth it to have a good header
here. It should helps to set context, it should identify the author
(hero or culprit!), including contact information, so that anyone who has
questions can call or email. It's useful to have the date noted, and a
brief statement of intention. On the other hand, this isn't meant to be
busy work; it's meant to make maintenance easier--so don't go overboard.
One other good reason to put your name on it: take credit! This is your
craft
*/
and then a little further down:
#include "xxxMsg.h" // xxx messages
/*
MAB 08-05-2004: With respect to the comment above, I gathered that
from the filename. I think I need either more or less here. For one
thing, xxxMsg.h is automatically generated from the .mc file. That might
be interesting information. Another thing is that xxxMsg.h should NOT be
added to source control, because it's auto-generated. Alternatively,
don't bother with a comment at all.
*/
and then yet again:
/*
MAB 08-05-2004: Defining a keyword?? This seems problemmatic [sic],
in principle if not in practice. Is this a common idiom?
*/
AHHHRRRGGHHH Just found this in some ancient code, bet the guy thought he was pretty funny
private
//PRIVATE means PRIVATE so no comments for you
function LoadIt(IntID: Integer): Integer;
The worst comment is one that gives a wrong explanation of what the code does.
That is worse than no comment at all.
I've seen this kind of thing in code with way too many comments (that shouldn't be there because the code is clear enough on its own), and it happens mostly when the code is updated (refactored, modified, etc.) but the comments aren't updated along with it.
A good rule of thumb is: only write comments to explain why code is doing something, not what it does.
Would definitely have to be comments that stand in place of error handling.
if(some_condition){
do_stuff();
}
else{
//An error occurred!
}
I just found this one, written on the line before a commented-out line of code:
//This causes a crash for some reason. I know the real reason but it doesn't fit on this line.
100k LOC application that was ported from vb6 to vb.net. It looks as though a previous developer had put a comment header on one method and then copied and pasted the exact comment onto every method he wrote from then on. Hundreds of methods and each one incorrectly commented...
When i first saw it i laughed... 6 months later the joke is wearing thin.
This is an absolutely real example from a database trigger:
/******************************************************************************
NAME: (repeat the trigger name)
PURPOSE: To perform work as each row is inserted or updated.
REVISIONS:
Ver Date Author Description
--------- ---------- --------------- ------------------------------------
1.0 27.6.2000 1. Created this trigger.
PARAMETERS:
INPUT:
OUTPUT:
RETURNED VALUE:
CALLED BY:
CALLS:
EXAMPLE USE:
ASSUMPTIONS:
LIMITATIONS:
ALGORITHM:
NOTES:
******************************************************************************/
/** function header comments required to pass checkstyle */
The two most unhelpful comments I've ever seen...
try
{
...
}
catch
{
// TODO: something catchy
}
I posted this one at the Daily WTF also, so I'll trim it to just the comment...
// TODO: The following if block should be reduced to one return statememt:
// return Regex.IsMatch(strTest, NAME_CHARS);
if (!Regex.IsMatch(strTest, NAME_CHARS))
return false;
else
return true;
One I've never found very helpful:
<!--- Lasciate ogne speranza, voi ch'intrate --->

Resources