Hacker News new | past | comments | ask | show | jobs | submit login
Coding Without Comments (codinghorror.com)
39 points by ajbatac on July 25, 2008 | hide | past | web | favorite | 57 comments



My impression...as you become more experienced, your comments will tend more towards confession and pleas for forgiveness...

  //XXX I don't know why this works
  ...
  //XXX Worst kludge of my life
  ...
  //FIXME this whole pile of crap needs re-written


My favorite comment that I've personally written:

    // Here there be magic. See datasheet for details; they explain it 
    // almost as well as I just did.
(followed by ~10 lines of math chock full of magic numbers.)


I maintained a piece of 250,000 line C code that had one comment in it (apart from copyright notices):

/* bad code */

To this day I do not know if this was a comment on the quality of the code that came after it, or if the developer was reprimanding the code.


Comments like this seem cowardly to me. If you can do better, then do. If you can't, write the best code you can and be enough of a man or woman to commit what you did and not clutter it up with excuses.


In a perfect world those kinds of comments would never be written. Unfortunately there are times when there simply isn't time to do it the Right Way (tm).

In those times when you have to do it the Fast and Ugly (tm) way, it's nice to make a comment that you really don't like the code. It adds some humor, and lets the maintainer know that there is no emotional attachment to that section of code.


there simply isn't time to do it the Right Way

Of course, this is the first thing that everybody says. And since everybody says it, everybody thinks it must be true. But my experience has been that if you really want to do good work, it turns out not to be true (say) 80% of the time. So the next time you find yourself making a mess because you believe you "have to", you could try stopping and questioning that assumption. You might surprise yourself. How do you think I learned this? Certainly not by following what the majority of programmers believe.

Edit: Rather than using phrases like "the Right Way", I'd suggest toning things down and looking for a way. There are many ways. If you get in the habit of thinking there's only one, and it's capitalized and trademarked, the bar seems a lot higher than it really is.


In the dev team I'm on we are constantly working within "aggressive" deadlines. Almost daily we come across a problem, brainstorm the ways of fixing it, and choose a path. Most of the time we can pick the one everyone agrees is the best way, or the Right Way.

Every once in awhile we're stuck at 3 days to code freeze (the product isn't a website, so we physically send out a DVD with our product on it, so quietly pushing out hotfixes isn't an option) and come across a bug that almost no user will care about that has two solutions:

1) Fix the problem the correct way. We don't know exactly what the correct way is, but we know it'll take a month or longer to code.

2) Apply some hack that gets it to work. This is usually something ugly and imperfect, but it's possible to do in 2 hours. We can tackle the problem again and attempt to get at a better solution.

If we don't ship on time, we lose piles of money. Guess which one we end up choosing ;)

Option 2 is fairly rarely chosen, but all it takes is for it to happen once or twice to have comments like the above in code, and forgotten.

Right... that whole Right Way (tm) thing is mostly tongue in cheek. It almost always refers to the way I want it done, and is a fairly flexible way.


Clearly you have never worked in a situation with a looming deadline. Sometimes there is simply no time to clean things up, you just have to extend from whatever code you have, no matter how ugly, because you aren't given the go-ahead to spend the extra time cleaning.


Clearly you have never worked in a situation with a looming deadline.

I've made my living writing code for the last 12 years. How likely do you really think that is?

There's a deep streak of passivity among a lot of programmers. That's part of why they (we) tend to be downtrodden. The belief that one must do shoddy work unless "given the go-ahead" to do good work is as much a part of the problem as anything else.


Exactly, stop seeking permission and just do good work all the time. It takes how long it takes and those people making up deadlines will be forced to adjust to the speed at which you work. They don't know whether you're doing it right or wrong or clean or ugly, they don't know what the fuck you do anyway, so do it how you like to please yourself.


Nonsense. Often your code will be ugly because some API in other code is broken or missing (see a lot of JavaScript), or doing something the right way is too slow or complicated, and you don't happen to have enough time to make a research project out of it. So then you add a self-deprecating comment to provide a little joy in the existence of the poor schmuck who will have to maintain your mess. Everybody wins. Kinda.


I'm a perfectionist, and sometimes the only way I can make progress in my project is to do it the hacky way while documenting the promise to return later to fix it into a comment in the style of: "Lazy shortcut."

Sometimes doing it The Right Way would necessitate a big refactoring of the supporting code or learning a concept in more depth and I can't afford all that overhead (which might break flow also).

Also, sometimes a far-reaching refactoring might be carried out in stages over a number of hours or days and to go from where you are to The Right Thing you'll have to pass through a number of less-than-optimal stages. But I always find it easier and faster to use an incremental approach where I accept suboptimal solutions, most of which will be quickly overwritten anyway than trying to do The Right Thing all at once.


You don't have to know the right answer to know if the answer you've chosen isn't the optimal one.

While I'm sure it'd be nice to know all of the answers all the time, some of us mere mortals can continue to try to notify other people that extra attention should be paid to the code following those comments.


One of the most insightful things I've read here all week.

Sometimes I think I should make a macro out of //HACK:


He missed the distinction between in-line comments and API comments. Pretty much all skilled developers would agree that in-line comments should be minimized, and used only when necessary to explain the reasoning behind a particular design, or to clarify a complex section that can't be refactored. But for API functions which you intend other developers to use as black boxes, you need to provide extensive comments clearly explaining the purpose, inputs, outputs, error conditions, and maybe even some sample code.


That's documentation, not comments. Nothing hurts code readability more than huge chunks of markup (markup!) getting in the way of the code you need to read to maintain. Javadocxygenwhatever generates pretty web pages, but leads to write-only source files.


I appreciate the readability problem, but what would you propose as an alternative? In my experience, combining the code and documentation in a single file makes it much more likely that developers actually will update the documentation. Besides, any decent editor will hide the documentation if you don't want to see it.


How about abstraction? Draw a clean line between the API you're trying to document and the code that implements it, and make sure that comments for either don't cross-pollute. This is a good idea anyway.

I can't tell you how many automatically generated documentation trees I've seen that are utterly worthless. Documentation of public interfaces gets mixed in with usage notes on internal structures, and you don't know what you're supposed to use.


Not sure about you, but I learned to code by writing psuedo code.

I routinely start with comments that psuedo code my idea and then add the sections of the code.

If I can't remember how everything is supposed to work while I'm writing it, what hope does the intern 2 years from now have in adding a new feature?


Yeah, sometimes if I'm doing a complex logic block I will just put the conditionals in and fill them in with a short description of what will be there. Generally, since I've already written them I just leave the comments in after I fill the real code in.

I've noticed that my Javascript is usually very readable and doesn't require commenting for the most part. I think using MooTools has a lot to do with it, those libraries all encourage good naming practices.


if a code is changed comments need to change too! Too many times I have seen out dated comments adding confusion to the code. If my code requires great deal of explanation, I go back to my drawing board and redesign the logic.


Very applicable point. I keep on noticing this happen and I would prefer no comments to outdated comments.


Those comments he doesn't like are often required by coding practices in a team setting. Rightly so as there are often people of many different skill levels working on the same code.


While it is true that when some idea can be expressed by descriptive variable or function name, comment is not necessary.

But there are many places in the code, where it is highly desirable to explain by plain words, why certain solution was adopted, that certain part is a bug fix, or why some part of the code is counter-intuitive. I for one am much more happier when my colleagues comment their code extensively.

To look at it from the opposite side: Is there any inherent problem with having too much comments? (provided they are correct).


If you can't write intention revealing code, this often is a symptom! Most often this means that there are implicit rules written into your code base. 90% of the time or more these should be factored out!

Also, another problem with too many comments: this is more stuff to maintain. Chances are, the programmer already has enough to do!


What about assertions? They work well as comments, but they're actually tested, and you know immediately if they go out of date.

You can decide one way or the other whether to compile them as no-ops in releases, but it seems like a big improvement either way.


To some extent it depends on your language. jQuery seems about right for that kind of JavaScript.

http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js


Actually, that seems like comment overkill to me. Almost every line has a comment.


If you document you need to keep the comments in sync with the code. If you write self-documenting code, you need to keep the function names in sync with the code. You just can't win...


The worst comments are the ones that say, "this is awful, will fix later".

I try to datestamp my comments, but I've seen some of the above with dates three years old. Why?


I already commented on this so I guess it must be a bit of a hobbyhorse, but I think I can answer your question. The comment really has nothing to do with coming back and fixing it later. It has to do with alleviating a feeling of guilt (or is that shame) about shoddy work. So the comment has served its purpose and that is why it is there.

Once you make a point of never doing this, the psychological pressure has to find another outlet, such as just fixing the code in the first place.


It wasn't the point of the article I now feel smug about being able to identify that Newton-Raphson implementation before reading the line below.


as time goes, you need less comments


as time goes, people tend to write less comments


Most of the time I deleted my own comments after things become more obvious - I hate 'moving parts' in my code

The trick is to highlight comments with bright & contrast fg/bg color combo that hurts your eyes (it also serves to say 'hi i'm comment, i'm important, but delete me when u understand me')


I disagree. Code without comments will never be as understandable as code with comments.

This is true because code is designed partly for computers while comments can be written entirely for humans.

This is important because comments only have to be written once and maintained occasionally while code without comments has to be reinterpreted every time it is read.


Not quite! I think code can be written to make it self explanatory. With appropriate variable, function names along with proper abstraction and refactoring code can be read almost like a prose which eliminates need for comments. At times comments are too annoying because they state the obvious or they are not updated along with the code.

eg: code like this in ruby can explain itself very well!

display_error if not valid_input

Now I do understand that comments cannot be replaced entirely and sometimes it is necessary to add notes to understand the code thus I prefer using comments sparingly and avoid long headers on top of each file. Those headers with author name, dates and other information is unnecessary if right tools are used to maintain your project.


You mean:

  display_error unless valid_input
right?


Right. Unless he means:

    display_error if invalid_input


Why use more different language constructs in a post than necessary?


I don't like "unless". Why do you? Every time I have to actually think about what's happening, I change it to "if" so all the logic is actually written visibly.


I use "unless" in ordinary speech. Unless I'm talking with someone who dislikes the word.


I don't parse/think-about boolean logic like English.


Then you probably won't be happy with languages like Perl and Ruby, DSLs, or the "There is more than one way to do it" line of thinking some people have.

It's a big world out here, there's room for Spock and for Kirk.


I love ruby, and use ruby at my job. I just don't write unless. Certainly there is no cause for someone to say a statement is mistaken just because it used if+not. Nor to guess that someone won't like ruby just because he doesn't like unless.


Saying someone is mistaken because they used "if not" instead of "unless" doesn't align with my understanding either, as I tried to point out by listing yet another way to write the same thing.

OTOH, you made a much more interesting statement than simply saying you didn't like "unless," you took things into a discussion about programming languages resembling vs. not resembling English.

Ruby has a bunch of lispy things that have nothing to do with English, but it also has a bunch of Perl-inspired things that have a lot to do with expressing logical ideas in English-y "prose."

If you can reconcile those two things, then yeah, you'll like all of Ruby. If not, you'll probably find a subset that pleases you. So sure, I can see that you might like the Ruby you use.


You said you use "unless" in English as if that proved it was good to use it in boolean logic too. It doesn't. For example, I am happy to use !, &&, and || in my code, even though they aren't English. The criterion for what makes good code is different than what is good English.

My point was that I think an explicit not is clearer than unless in cases sufficiently complex as to require stopping to think about it. If you're trying to keep track of multiple negations, then having one be in a different form than all the rest does not help. (And meanwhile, there is nothing wrong with a habit of always using if).


"The criterion for what makes good code is different than what is good English."

In total, yes, but that does not mean that there are no things that work in English that also happen to work in code.

Furthermore, it is difficult to generalize about this: some programming languages are entirely unlike English and work very well, others attempt to be like English and are terrible, while others attempt to be like English in some ways and work.

And further to that, some parts of some programs attempt to be like English and work well, while other parts of programs work well when nothing like English.

Now while I understand bang, andand, and oror, they are a terrible legacy of our C++ days. Bang is especially unforgiveable. If we must have a prefix operator, what is wrong with ~, the actual standard symbol for negation?

;-)

p.s. This thread may seem to be a digression, but it seems quite pertinent to an article that talks about writing code for readability.


What's the matter raganwald, jonesing for a blog post now that you've hung up your blogging shoes? :-)


Sadly, cutting out my blogorrhoea has no statistically significant effect on my logorrhoea.


I agree with you that !, &&, || aren't the best idea ever. I wonder if the reason behind them over words is so you don't have to put spaces around them. Omitting spaces seems to be popular with the infix crowd (e.g., they happily give up *,+,- from identifiers just to leave out some spaces).


"I wonder if the reason behind them over words is so you don't have to put spaces around them."

Hunh, that hadn't occurred to me! That's a really interesting conjecture, touching on design trade-offs in neat ways. Thanks!


Code without comments is better than code with outdated comments - this happens quite frequently.


Amen. Comments lie. This happens all the time. Programmers who try to maintain code by reference to the comments will get it wrong. You have to debug the code. Comments, at most, should be a guide to what happens where.


You can write a provable theorem as a stream of symbols from mathematical logic, instead of prose. But, do you really want to read the result? Code can be made clearer through abstraction, certainly, but comments are a domain specific language for helping humans understand computer programs.


It depends on how well you write your code.

Also I think in general hackers should learn to read code. To reverse engineer. To understand what is going on without comments. Then when you do have some comments, it's a bonus (Or just even more confusing and contradictory).


"This is true because code is designed partly for computers while comments can be written entirely for humans."

There are differing degrees to which this is true. Different languages had different design motivations. Smalltalk was specifically designed to be readable by humans. By grade school aged humans, actually! In the Smalltalk community, most regard comments as a "Code Smell."




Registration is open for Startup School 2019. Classes start July 22nd.

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: