How to comment code that has a complicated explanation [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 9 years ago.
Improve this question
I have a if (a > b) { .. in my code, which I would like to explain why is there to someone looking at the code.
The reason for it being there is quite complicated and cannot be explained well without the use of images.
The question is, how to best document this to a programmer looking at the code? Is there a generally accepted way?
Should I create a comment in the code saying "See explanation XX", and then create a document somewhere containing XX?

Much of this will depend on what you are coding and the size of your project, but generally I would say that you should comment this particular conditional with an explanation only for what if (a > b) { .. is checking for, and why.
When you get to the content inside the if condition, explain that. Broader explanations as to the purpose of the function itself and its objectives should generally be in the declaration, although you can also add descriptions to the definition (I prefer to avoid this generally, although I sometimes describe the method in further detail on top of the definition, where it would simply clutter the declaration of the class).
For example,
class A
{
// this method performs operations on x or y as appropriate, given the input conditions of
// a and b. Its purpose is ... and in order to achieve this it does ...
void Method(int a, int b);
};
// elsewhere in a .cpp file
// Note that this method uses method abc rather than method cde in order to achieve
// such and such more efficiently (description here is more technical than in the
// declaration, and might focus on more specific issues while still remaining
// applicable to the function as a whole, and should therefore not be in the body)
void A::Method(int a, int b)
{
// check to see whether or not a > b in order to decide whether to operate on x or on y
if (a > b)
{
// a is greater than b, and therefore we need to operate on x because...
}
else
{
// a is not greater than b, therefore we need to operate on y because...
}
}
I find that by structuring my comments to address the reason why specific sections of code are the way they are, the reader is able to "follow the story" that the code is telling as she reads through it.
If it is absolutely impossible to describe what the if section is doing without a broader explanation, then by all means add a paragraph or two. There is nothing wrong with long comments as long as they are well placed and address the specific purpose of the following lines of code. You shouldn't need to add for more information, see function header because that should already be implied.
You can add broader descriptions to the enclosing function, method, or scope, but comments should always address the piece of code they are referring to as succinctly as possible. After all, if the reader wanted to know what the whole function was doing, she'd look at the declaration. The reason she's looking at the definition of the function is because she wants to know what the components of the function are doing, and so the comments should address just that.

Related

Is commenting every right brace good/bad style? [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 years ago.
Improve this question
I am teaching an upper-division software engineering course and am reviewing every student's code. Some of my students have picked up the habit elsewhere of adding a comment to the right of every closing brace identifying the statement type, such as:
if (x > 3) {
y = 10;
} //if
I have told the students to follow the Android code style guidelines, which says nothing about this practice. On what grounds should I tell them not to do this (besides personally not liking it), or should I permit it?
Comments are for clarifying code and increasing readability. It's clear enough to most reasonable software developers that the statement is an "if." Furthermore, many IDEs and editors automatically highlight brackets such as these, so the comment isn't necessary. Generally, you should save comments for describing what methods, classes and variables do (e.g. in Javadoc), or what subroutines within a method will do. This is based on the general guideline of making sure everything you add improves the code.
Tell them that they should assume that person who review code knows language syntax and how to program. Comments should be rare, indicate and explain some weird and not obvious code section (for instance the api provided by some library is bugged and some workarounds/hacks are needed). We've got documentation (and unit tests) to explain how to use and how code should behave. For educational purpose you can write small class/module filled with such "comment-documentation", give it to students and ask them what did they learn about code from these comments.
Well, most likely this will end up in a discussion based on personal preference - which is not within the scope of stackoverflow. But aI'll answer anyway:
In my opinion, that's a bad thing to do - for multiple reasons.
It messes up the code. the more comments are in there, the less readable it is. A single } in a line tells me, instantly, that the last block ends here. with the comment behind, there is more to read - and no additional info (but people will read anyway, cause they don't know that the comment doesn't include any info... and because people tend to read everything automatically)
It leads to sloppy indentation. After all, that may even be the reasons people started that in the first place.
it's unnecessary - if I indet the code in a consistent manner, it shouldn't be necessary to note what was closed, it should be easily visible by just going up to where the last statement with the same indentation level was. In most cases (unbless you're reverse-indenting (or whatever that is called), which I don't like at all) this should be very easy, as there is nothing in between...
it leads to bigger file sizes. may be invalid on modern systems, but still.
Every time is overkill. It depends on the level of indentation and the length of your function, but these are usually signs that you need to step back and refactor. The only time I explicitly do it is for namespaces in C++

Refactoring code that imports a csv file that has headers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to refactor some code that reads a csv file. The first character in every line of the file indicates the type of record: H = Header, I = Information, and D = Data. Each record type has a fixed and different number of fields. My program uses FasterCSV to read a line from the file and then uses a case statement to determine how to process the line.
record_type = new_record[:record_type]
case record_type
when "H"
factory_build_H_record(new_record)
when "I"
factory_build_I_record(new_record)
when "D"
factory_build_e_record(new_record)
end
For refactoring, I'm trying to follow Sandi Metz' blog post on the use of case statements in OO programming and eliminate case statements. My inclination is that I need to create some classes that represent the three record types and then define some methods like process_record. I'm not sure how I should go about to create the classes. Any help would be appreciated.
The blog post you linked is specifically about using case statements to tell what kind of object something is. That is often a symptom of bad design, and that is the point she is making.
The way you are using a case statement is much more acceptable. In fact, no matter how you restructure this, you are going to be doing some kind of test (case, or if, or otherwise) against that column in order to determine the correct behavior for the row.
If your code later on has to try to tell those objects apart by their class (using a case statement or if), then you are violating the spirit of the blog article.
The solution, is to create objects that have the same interface (have the same methods, used in the same way. The behavior of those methods is different internally in each class to do the right thing for that object.
Hope this helps clear up the concept for you :)
Case statements are not bad for small and fairly static conditional cases like the one you have.
If (theoretically) you anticipated having more record types in the future (besides H, I, and D), then the problem with the case statement is that it might cause you to start violating the Open-Closed Principle.
In this case, you might create a set of RecordType classes that is something along these lines:
class HeaderRecordType
def is_mine(record)
...
end
def build(record)
...
end
end
class DataRecordType
...
end
class SomeNewRecordType
...
end
Then, instead of the case, you would just iterate over a list of all the RecordType's (or use a Chain of Responsibility) and ask each one is_mine(record). As soon as one of them says yes, then you stop looking and call build.

How To write comments [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Hi I have like 50 pages of code that I should write comments to it ...
Can you guys show me the best way. I meant I need you to write me a sample ...
the comments should contain nearly everything (classes, constructors, attribute, methods, events, functions)
Don't comment what is obvious like
//The width of the line is 2
lineWidth = 2;
or
//Clones the snapshot
tempDraw = (Bitmap)snapshot.Clone();
There might be a good idea to explain WHY a certain code line is there. For example explain why
panel1.Invalidate();
Needs to be invalidated.
The basic idea is: add extra information with comments and use them for explanations, don't create redundancy and duplication.
EDIT:
You might also want to explain why each item in the toolbar needs to be unchecked here:
private void toolStripButton1_Click(object sender, EventArgs e)
{
foreach (ToolStripButton btn in toolStrip1.Items)
{
btn.Checked = false;
}
...
}
because is not obvious from the name of the event handler which button is clicked in order to understand why all buttons are unchecked.
A good comment would be something like:
private void toolStripButton1_Click(object sender, EventArgs e)
{
//Deselect all previously applied filters because the user clicked "disable all",
//which removes the effects of all filters and we want to show this the the user
foreach (ToolStripButton btn in toolStrip1.Items)
{
btn.Checked = false;
}
...
}
Good comments will document intent, not function.
It's largely useless to comment assignments with "assign x to y" or similar.
It's much better to comment the code with a higher-level view of what the code aims to ultimately achieve, with pre- and post- conditions. You need to comment on (say) peculiar implementations or checks that are necessary yet counter-intuitive, and possibly reference specification documents etc.
If you've got to comment 50 pages of code, I suspect you're doing this at the wrong stage of your project. I tend to comment a class or method's intent with pre/post conditions prior to writing it. It's a form of mini-specification.
I recommend you to use XML comments in visual studio. Doing that you also can automatically generate documentation for your code, also other developers can see which method does what through intellisense.
http://www.winnershtriangle.com/w/Articles.XMLCommentsInCSharp.asp
http://msdn.microsoft.com/en-us/magazine/cc302121.aspx
You should not spend time writing documentation now, you should refactor this code. The design is not correct from a class-structure perspective. Your code should be structured as much as possible so that a class has a single responsibility it tries to achieve, and have a corresponding name.
Your Form1 (bad name, b.t.w.) does too much. It should ask other objects to help it. You might want to introduce a Tool class, which knows which label text and cursor are appropriate. You might want to use inheritance for the different shapes to do the drawing in a shape-specific way. In that way, your Form1 only has to delegate to the current tool.
With better structure you can reduce the amount of documentation you have to write.
You might want to look up CRC-cards.
I actually just wrote a blog post on this subject. Bear in mind that it is 100% possible (but perhaps not preferable) for code to contain no comments and be perfectly readable.

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