Code Tells You How, Comments Tell You Why

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. :wink:

kidding aside, where I work, the only comments i’ve found from my predecessors are:

  1. comments i’ve written
  2. 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.

1 Like