Ha, I (and maybe you) got scrwed by your blog-software eating our spaces. Those should be quote-space-quote not quote-quote.
One use for comments raised in a code review:
searchable string for maintainance. Weâre all familiar with //FIXME, but how about
//Defect v4.04#112: customer wishes amounts above
//MAXAMOUNT reduced to max and processed
to identify where and why but not how
if( amt MAXAMOUNT ) amt = MAXAMOUNT;
I accepted this suggestion to improve maintainance; your comments?(I know, all CAPS is EVIL, butâŚ)
Martin Fowler makes the observation that code comments, while not strictly a code smell, can be used as a deodorant for code smells. Frequently, theyâre an indication that something needs refactoring. Itâs not that they are bad, but lots of times they are used to account for poorly factored code.
Said better, while not ignoring this is still very much an issue of preference: http://c2.com/ppr/wiki/WikiPagesAboutRefactoring/CommentCostsAndBenefits.html
$reversedString = blah blah blah
is IMO better, and more concise
Good point. I use comments as notes to myself as much as notes to others. Itâs not just the âwhyâ, but also what Iâm thinking at the time. That way, when I have time to refactor that portion, itâs a bit easier. I hate looking at code Iâve written and thinking, âWhat the hell was I thinking?â
"$string = join(ââ,reverse(split(ââ,$string)));
reverses your string, but how hard is it to insert
Reverse the string "
Well, thank goodness. At least you are ok with some comments on âwhat the code doesâ.
This has become such a dogmatic thing these daysâŚjust like so many other decent ideas, they are horrific when taken too far.
I certainly donât mind a comment telling me what it was supposed to do, as well as how. Can make it easier to debug if it breaks later. At least you know what the intent was, and you can see if it matches.
It always amazes me how arrogant so many programmers are.
âif the code needs comments to explain what itâs doing, it isnât done yetâ
âobviously you donât expect your code to be read by someone who isnât familiar with the language syntaxâ
âIf youâve hired programmers that are too stupid to read either the comments or the code, youâre SOLâ
It is not always feasible to have a programming guru on hand to fix every issue. Not everyone has the same skill set. Sometimes companies are stuck having to maintain code in languages their current staff arenât well-versed in. Gurus arenât available either at all in some areas, or for the money some companies have alotted for their IT staff.
People should assume someone with 1 or 2 years experience will be coming in after them to maintain their bugs. Iâm not saying you have to explain every little detail, but if you have any doubt whether someone coming after you will understand your code in fairly short order: add a comment. Donât be an ass and assume they should understand the entire context and layout of the application the way you do, or that they have a few days/weeks to get oriented to confidently fix your bugs.
I agree that clear code is better than comments and usually should be sufficient. If it isnât sufficient, think about what youâre doing (could I simplify this?) instead of just adding the comment. Sometimes the comment is still needed, but often the best solution is to just simplify the code or improve a variable name.
There is one thing I would like to add to this post. Comments are also good for summarizing. Even when the code is commented and crystal clear, it isnât enough. Somebody unfamiliar with the codebase shouldnât have to wade through the whole file to figure out how a class fits into the system.
There should be a header at the top of the file explaining the purpose of the file. There should be a header before every function explaining the purpose of the function.
C# and Java both have language support for this. Our team has internal requirements for these headers, and it makes debugging much easier.
Good code, using human-readable variables, generally comments itself. The only time I over-comment code is when Iâm showing data flow to a complete newbie that has no idea whatâs happening at all. Many times it is their first experience with seeing code.
Mostly, though, your operations should indeed be self-explanatory. My own code is still readable to me many months later, because the fellows that taught me how to code (in HyperCard, no less), were professionals that made sure it was drilled into my head.
More often in my code youâll see variables like:
subInfo
subPhone
subAddr
than youâll see
si
sp
sa
While the latter is easier for me to type, thus making me a faster programmer, the former is easier to read, thus making it easier to change the code later and read teh code later. Iâd say a little typing up front saves in the debug process later. I think thatâs a lot of why I donât pick up new languages quickly anymore. Too many examples are given in the shortest, most efficient way possible, rather than the most humanly readable way possible.
If you need context for the reverse string
operation, why not write a âreverseâ method?
Couldnât agree more. I wrap a lot of "weird"
code like this with well-named functions.
That still doesnât say why you reverse the string.
A good comment, IMHO would be like:
reverse the string, because [foo]
Even if you created a reverseString subprocedure.
At my current job Iâve had a number of predecessors of various skill level, none of whom Iâve met. One guy had a blunt-force style. His code was fairly easy to read because I donât think he actually knew any algorithms. He had a bad habit of commenting EVERY SINGLE LINE OF CODE IN ALL CAPS. Maybe 1 in 100 comments could be deemed minimally useful in some way. At the end of every function he had, I shit you not:
RETURN TRUE.
return true;
I wish I had his email to send him this article.
While I agree that your code should be refactored enough that it is very easy to read I do not think that good code should replace the use of comments. I still firmly believe that each logical block of code should have a comment explaining it. Even if you think it is extremely obvious.
int oldX = deviceInfo-position.x;
int directionCode
= (x oldX)? DIRECTIONCODE_RIGHT
That is well written code, but who has any clue what that is doing? There should be a comment above that explaining what is going on.
http://www.google.com/uds/js/uds_compiled.js - does this follow SICPâs statement about program?
I avoid writing comments - it yields good job security! if no one else can read your code, they gotta keep ya.
kidding aside, where I work, the only comments iâve found from my predecessors are:
- comments iâve written
- comments that merely say something like âDonât modify anything below this lineâ when the junk below that line has been deprecated.
I believe this site to be of use:
a href="http://thc.org/root/phun/unmaintain.html"How to write unmaintainable code/a
I definitely agree. Good code needs basically zero comments. About the only time I use comments these days is to document an algorithm or external things.
If you want a reasonable example of well documented code, take a look at the Java API. All the code is available.
Iâve never felt in any way stuck or confused when reading even the most complex piece of code in the Java APIâit reads like a childrenâs book.
You may think you donât need it THAT digested, but it sure helps! When you are just glancing into someone elseâs class to make YOUR class workâyou really donât want to waste time understating their garbageâyou just want to understand some operational detail that isnât obvious from the API.
I donât believe Iâve seen one yet that had more code than comments (and Iâm just talking inline comments, not javadocs)
What is the argument against good comments? They help you revisit code for a self-review which you should be doing anyway. If they slow you down, either you arenât thinking enough in the first place or you need a typing class.
Know how when you are explaining a problem in your code to someone else, you often come up with the fix yourself? Comments also act in this capacityâproblems requiring refactoring that you donât see at first come out very clearly when you try to explain your code in comments.
Also donât use something like this:
âif the code needs comments to explain what itâs doing, it isnât done yetâ
The âWhat Itâs doingâ phrase simply means donât repeat your code in comments (which is correct). However, that doesnât cover all the Why issues you should be putting in there.
Every time I encounter code and canât talk to the person who coded it, I have to start thinking âWhyâ did he make that choice? Was he more insightful than me, or am I seeing something he missed.
Here is an example from some code Iâve been working on. A string number without a decimal is being multiplied by another number that âTendsâ to be a factor of 10. The code currently converts it to a BigDecimal, multiplies it by the factor and converts it back to a string.
This is taking up a lot of resources on our embedded application.
Furthermore, the unit tests pass in numbers like 3333 instead of a factor of ten to multiply by.
No comments whatsoever exist because the writers were âXPâ and would always be able to talk to each other.
Now the writers are gone.
I can improve the hell out of this by simply moving the decimal back and forth within the string and never converting it.
But WHY the 3333 test? Could some caller (this is called from ALL OVER the place) be using arbitrary numbers to multiply/divide by?
Why the conversion to BigDecimal? Were they not smart enough to understand the fact that BigDecimal tends to allocate bunches of byte arrays, or am I totally missing something?
When the big decimal is formatted to a string it has a min/max decimal places, how is this âMinDecimalâ being passed into the method interacting? Which takes precedence?
So instead of a simple refactor, this becomes running all over the program to find out WHY things were done and how many different choices I had.
btw:
I ended up refactoring the method but leaving the old one thereâif the value passed in isnât a power of ten or something really tricky happens, it falls back to the original. Iâve never seen this happen yet except in those stupid arbitrary tests.
Your post is contradictory.
The no-comment fetish has come about because comments have to be taken as being incorrect or wrong and as such thoses long blocks of comments are usally worthless.
As code is changed comments are more often then not, not updated also you donât know if the comment was made before the code was written so it is now out of date, and thoses are just two of the ways comments differ from what the code actually does.
Since it is very common for code to differ from what the comments say it does whenever you have to change some code do you read all thoses comments or ignore the large comments and follow the code?
Better:
sub reverse_string {
my $string=shift;
return join(ââ,reverse(split(ââ,$string)));
}
$x=reverse_string(âdonât repeat yourself, even in commentsâ);
Some comments are good (like the Boyer-Moore comment above) but often comments are a âbad smellâ⌠a lot of programmers only write comments to apologize and make excuses for things they know are wrong.
[⌠iâll punish you âŚ]
Javadoc-style comments, which explain the function of objects and methods, are often less than effective. For instance, all of the AWT components in Java have methods called invalidate() and validate(). The Javadoc said that invalidate() âinvalidates the componentâ and that validate() âvalidates the componentâ. There was no explanation of what validation and invalidation where, but programmers found they had to do something with those methods if they wanted applets to repaint correctly.
I donât think that programmers have trouble understanding what objects and methods do, taken individually. The trouble is that, in a a system with 50 objects, programmers have a hard time understanding which one to use, how the objects fix together, and where the right extension point is to make the change they want to make. I havenât seen the right tool for that job yet.
Me canât wait for when natural language programs wonât not make code not unreadable.