Beta
×

Welcome to the Slashdot Beta site -- learn more here. Use the link in the footer or click here to return to the Classic version of Slashdot.

Thank you!

Before you choose to head back to the Classic look of the site, we'd appreciate it if you share your thoughts on the Beta; your feedback is what drives our ongoing development.

Beta is different and we value you taking the time to try it out. Please take a look at the changes we've made in Beta and  learn more about it. Thanks for reading, and for making the site better!

Myths About Code Comments

timothy posted more than 4 years ago | from the myth-conceptions dept.

Programming 580

theodp writes "Jason Baker gives his take on the biggest misconceptions about code comments: 1) Comments are free ('When you update the code that the comment references, you usually have to update the comment as well'). 2) Comments make code more readable ('by far the most pervasive myth that I've encountered'). 3) You should comment every function, method, class, and module ('documenting something that needs no documentation is universally a bad idea'). 4) Code must always be 'self documenting' ('would you rather use a one-liner that requires a 3-line comment, or a 10-liner that requires no comments?')."

cancel ×

580 comments

Sorry! There are no comments related to the filter you selected.

One person's myth is another person's fact. (5, Insightful)

yog (19073) | more than 4 years ago | (#30616696)

Well, everyone's welcome to their opinion, but it's pretty well proven after decades of software engineering that code should be commented. The price of maintaining comment-free code is well known.

There is a school of thought among programmers who consider themselves hotshots that if you are not a hotshot you have no business touching their code. The problem with this attitude is that it has little to do with the real world, where people change jobs and programmers inherit someone else's code. If you want to write perfect, comment free code in your perfect little world, go right ahead, but don't expect to make a living at it most of the time.

It's surprising to me that someone has submitted this as a "news" item. News flash! Everything you know is wrong. Sorry I don't buy that. If you don't comment your code, I won't pay you for it. I'll inform the management that you neglected an important step and don't deserve a good reference. I won't be able to give you the benefit of the doubt when your code doesn't make perfect sense. I'll trash talk your code in front of your colleagues. Look at all the mistakes in this guy's work; I'll sure never recommend him if his resume crosses my desk. We may need to just rewrite this stuff because it's not maintainable as written.

What's really annoying is when they put comments that don't elucidate the code or their intent; they're just snide little messages from one know-it-all to another. They're too embarrassed to actually explain the code because that implies a level of insecurity they would rather not admit to. So instead they say things like: /* yeah, I don't like this either */
or
# hack, to be fixed later

Wooooo, really helpful comments there. I've seen this sort of thing countless times in my career and most others I know have as well.

Re:One person's myth is another person's fact. (3, Insightful)

Brian Gordon (987471) | more than 4 years ago | (#30616736)

Woooo, business programming. Believe it or not, there are a few applications out there that require performance and cleverness rather than strict convention. I think that a myth of software development is that every line of code should always be simple and easy to understand. Sometimes things are complicated, especially in performance applications.

Re:One person's myth is another person's fact. (0)

Anonymous Coward | more than 4 years ago | (#30616768)

Bit-shifting as multiplication?!

Mind == blown.

Re:One person's myth is another person's fact. (3, Insightful)

Nutria (679911) | more than 4 years ago | (#30616944)

Sure. It's a damned fast way to multiply or divide by a power of 2.

I'd never do it in a DP shop, though...

Re:One person's myth is another person's fact. (0)

Anonymous Coward | more than 4 years ago | (#30616970)

If this concept is hard for you, you're in a wrong business. Get out while you can.

You made his argument for him (2, Insightful)

dreamchaser (49529) | more than 4 years ago | (#30616934)

Woooo, business programming. Believe it or not, there are a few applications out there that require performance and cleverness rather than strict convention. I think that a myth of software development is that every line of code should always be simple and easy to understand. Sometimes things are complicated, especially in performance applications

GP never said that (re:bolded text), and the point you are trying to make makes a strong argument FOR clear, concise comments on code. Good code isn't always easy to read at first glance and appropriate comments are important in any project with more than one programmer.

Re:You made his argument for him (4, Insightful)

DG (989) | more than 4 years ago | (#30617178)

Indeed.

Sometimes there is a very good reason for including clever, non-intuitive code in a project. But that clever code needs to be very well documented because the next guy to touch it may not be that clever.

When in doubt, optimize code for future maintainability and legibility. Hardware gets faster. Programmers don't.

DG

Re:One person's myth is another person's fact. (1)

DrLang21 (900992) | more than 4 years ago | (#30617156)

I think that a myth of software development is that every line of code should always be simple and easy to understand.

No one here is saying that. They're just saying that you should comment it, so that if it is complex, the next guy can figure out what you did without spending days thinking about it.

Re:One person's myth is another person's fact. (5, Informative)

v1 (525388) | more than 4 years ago | (#30616748)

I find the most important comments are those that tell you WHY something was done the way it was. I do this with my own code when I track down and fix a bug that turns out to be caused by some very subtle effect or easily made mistake. I put the comment there to stop myself (or someone else) from "fixing" / "cleaning it up" later because they don't realize why it's done the way it is. Comments like:

# yes, 1, not 0. If all four of the lists are allowed to go to 0, we will blow up later with DBZ.

And having a sometimes very poor memory of code written long ago, this saves me from myself more than others.

Re:One person's myth is another person's fact. (2, Insightful)

MichaelSmith (789609) | more than 4 years ago | (#30616750)

I work on a really big hunk of C code and one place I would like to see more comments is in the start and end of blocks. This is because during the life of the code people come in and paste maybe 1000 lines of code from elsewhere into the block and totally stuff up the indenting so its hard to see what is supposed to match to what. This is particularly a problem with importing between branches (my job at the moment) because it can be hard to work out the original intent of the various nested blocks you wind up with.

Commented out code is a particular problem because my editor can count { and } but it doesn't know if some of those have been commented out, possibly asymmetrically.

Where I work comments get used to abuse people. You commit a message:
 
/*Hey $YOU dont do this again */

But a lot of the comments we have I can't even read because they have been collected by the code in one of the countries it has been to over the last 30 years or so. Many of them seem to be in French and Arabic.

Re:One person's myth is another person's fact. (2, Informative)

innocent_white_lamb (151825) | more than 4 years ago | (#30616838)

If you're writing in C, do yourself a favour and check out this editor: http://www.geany.org/ [geany.org]

It's the slickest C editor that I've ever had the pleasure of using. It seems little-known, though, and I don't know why.

(It handles other stuff than C too, but I haven't used it for any of those yet.)

Thank you.. (0)

Anonymous Coward | more than 4 years ago | (#30617002)

..very much for mentioning this. Screenshots so far look very promising.

---> Fresh installation of devel/geany started at: Sat, 02 Jan 2010 00:07:31 +0100
---> Installing 'geany-0.18' from a port (devel/geany)

Re:One person's myth is another person's fact. (2, Insightful)

Tanuki64 (989726) | more than 4 years ago | (#30616984)

I work on a really big hunk of C code and one place I would like to see more comments is in the start and end of blocks. This is because during the life of the code people come in and paste maybe 1000 lines of code from elsewhere into the block and totally stuff up the indenting so its hard to see what is supposed to match to what.

If the only tool you have is a hammer, every problem looks like a nail. You comments are in this case the nail you desperately want to hammer in, when in reality you need a refactoring. And you need to give the idiot, who pastes the additional 1000 lines, a hearty kick in the ass.

Code format (1)

omb (759389) | more than 4 years ago | (#30617176)

Is very important, and it be consistent is more so; a good editor Vim or Emacs and code beautifier is your friend. Often you will need to temporarily re-format code, as you work on it, but in a big code base root-nd-branch reformats must be very rare, it screws up the SCM history, so I often re-format, fix get patch, revert, apply patch. Git etc makes this very easy.

Personally I hate the KR if (foo) {

} style. I like

{
}

An 80 column line limit is also OLD, I never edit in narrow windows >160 common.

drop, but I cant always get what I like.

Re:One person's myth is another person's fact. (3, Insightful)

khallow (566160) | more than 4 years ago | (#30616790)

Even the "this is a hack/kludge/abomination unto nature" comments are useful to me. It tells me some starting points for improving the code. Also I write similar comments to remind myself where the iffiest parts of my code are.

Re:One person's myth is another person's fact. (3, Insightful)

93 Escort Wagon (326346) | more than 4 years ago | (#30616928)

Even the "this is a hack/kludge/abomination unto nature" comments are useful to me. It tells me some starting points for improving the code. Also I write similar comments to remind myself where the iffiest parts of my code are.

I agree. When I put those sorts of comments in, they are most often notes to myself rather than a legacy left behind for others.

I prefer to write code that's easily extensible, and in most cases it's what I try to do - but that definitely takes longer than hacking something together (at least for me). Since I'm not the boss, there are times when I've been given direct orders to "just get it done so I can show this to xxxxx, we're never going to need to change this anyway" - and I do it. Down the road I try to fix those when I'm in a slow-ish period; but also, they are valuable reminders when, a year later, the boss comes back and says "can we add yyyyy and zzzzz to that?" because it a) gives me a chance to talk with him about why I prefer writing it right the first time; and b) provides support for telling him why it'll take me a few days to add those features rather than the 1-2 hours he thinks this "minor change" should take.

On a side note: There's nothing worse than running into someone else's 6-7 year old bit of code containing comments like "hack, important to fix this next revision" - it's too much like finding those silly "under construction" animated gifs on a web page that was last updated in 2003.

Re:One person's myth is another person's fact. (1)

TheRaven64 (641858) | more than 4 years ago | (#30616814)

It's possible to write code that doesn't need any comments. Code where the next person to read it will understand exactly what it does and why, just from the code. The difficult thing is knowing when you've done this and when you've written something confusing. If you can tell the two apart with 100% accuracy, then you can skip writing comments.

Unfortunately, I've never met a developer that could. I've met quite a few that thought they could, however...

Re:One person's myth is another person's fact. (1)

Draek (916851) | more than 4 years ago | (#30617092)

If you can tell the two apart with 100% accuracy, then you can skip writing comments.

Unfortunately, I've never met a developer that could.

I can. To my own standards.

The thing that everybody always misses, is that the difference between a "good" and a "bad" comment is entirely subjective. Sure, most people would agree that a "returns X" comment for a get_x() method is useless, and most would say that your average Perl one-liner must always be accompained by a suitable comment, but its in that nebulous middle ground where opinions are split, depending on the programmer, his team, their respective abilities and experience, the time-frames involved and myriad other factors.

So most people try to guesstimate conservatively, and comment more than they feel they should. But even then, it only takes one unusual programmer or a stupid manager with the idea that "everything should be commented" no matter how trivial, and we get yet another "proof" of the average programmer's supposed arrogance and disdain for commenting their code.

Re:One person's myth is another person's fact. (2, Insightful)

hedwards (940851) | more than 4 years ago | (#30617122)

OK, this topic is officially over. That's the nub of it, if a programmer could intuit what would be confusing a decade down the road or to another developer that takes over, then you can cut out on the comments. The cost of documentation does exist, but people ought to be thinking twice before putting in overly complicated, absolutely must comment code. Sure some cases require that for legitimate reasons, but most of the time you're doing it wrong, and putting in the comment gives you the opportunity to reconsider whether that complex code could be simplified.

Re:One person's myth is another person's fact. (2, Insightful)

WED Fan (911325) | more than 4 years ago | (#30616840)

In your race to be first, you failed to read the article.

Re:One person's myth is another person's fact. (1, Insightful)

SanityInAnarchy (655584) | more than 4 years ago | (#30616940)

There is a school of thought among programmers who consider themselves hotshots that if you are not a hotshot you have no business touching their code.

I don't see anyone claiming that here.

If you want to write perfect, comment free code in your perfect little world, go right ahead,

Nor that. At least Read The Fine Summary (attempting to increase my character-per-line count to avoid lameness filter):

documenting something that needs no documentation is universally a bad idea

And from The Fine Article:

Comments don't make code more readable. They are ways to compensate for code not being readable.

Which does happen. Again, from The Fine Summary:

would you rather use a one-liner that requires a 3-line comment, or a 10-liner that requires no comments?

But probably the biggest thing you missed is right at the top of The Fine Article:

It seems to me getting good at writing comments is an under-appreciated part of a Programmer's development.

I actually agree with most of what you said, but I would fix this for you:

If you don't document your code, I won't pay you for it.

Self-documenting code is a reality. It does work. And if you're going to carry out all your threats simply because I didn't do this:

// Gets the id
public int getId() {
  return id;
}
// Sets the id
public int setId() {
  return id;
}

In that case, yeah, it sucks that I don't get a reference, but I'd be glad to be unemployed again, looking for a job where I can do this instead:

attr_accessor :id

Part of the reason I suspect you have a problem:

What's really annoying is when they put comments that don't elucidate the code or their intent; they're just snide little messages from one know-it-all to another.

You seem to have a healthy dose of envy and disdain for the people who work under you. You're also missing the point:

/* yeah, I don't like this either */
# hack, to be fixed later

The first is a potential problem, but a little humor from one developer to another... Sometimes the code is a mess, and no amount of comments will help that. The best you could hope for is "I don't like this, and here's why:", or "This is how it works... I know, I don't like it either."

But that second comment, "hack, to be fixed later"? You should institutionalize that, because it is, in fact, a good practice. Make them do this:

TODO: fix this hack later.

Then have your CI system automagically create tickets for that -- they are indeed bugs, and should be fixed. But they aren't just bugs in documentation -- you should be removing hacks in the first place.

But if your developers feel they have to write a quick hack instead of Doing It Right, it's probably not their fault, it's your fault as a manager for setting unreasonable deadlines. Requiring them to thoroughly document their hacks isn't going to improve things, it's going to take time away from real work, resulting in less good code, and more hacks -- maybe ultimately reducing your program to a single 300 character long regular expression, but man, is it well-commented!

And you are again missing the point. The point is not that we are hotshot programmers who don't think non-hotshots should be messing with our code. Rather, we are competent professionals who expect people to understand the basics of the language before reading our code, and even then...

class Story
  has_many :comments
  belongs_to :poster, :class => User
  belongs_to :submitter, :class => User
end

Do you really want that to be commented? Think about it -- I bet you understand what that does without a single comment, without even knowing the language or the framework. Comments only make it longer, harder to maintain, and less readable, when your code looks like that.

Re:One person's myth is another person's fact. (2, Insightful)

SteveWoz (152247) | more than 4 years ago | (#30616942)

Both the code and the comments should be as understandable as possible. Don't forget that the effort to comment well helps the programmer in his/her own thinking and his/her own understanding of their own code, and helps in development of good code that doesn't have bugs.

Re:One person's myth is another person's fact. (1)

buddyglass (925859) | more than 4 years ago | (#30616948)

IMO it boils down to "if it's complicated then comment it, otherwise don't". Unnecessary comments just get in the way. I'd add that lots of code is complicated and "hairy", and thus deserves comments, solely because its author was not skilled enough to create a cleaner solution.

Re:One person's myth is another person's fact. (0)

Anonymous Coward | more than 4 years ago | (#30617028)

Yes. Many programmers (most, I would wager) are not hot shots. Many of them may think they are, but they're not. Maybe the percentage of "meh" is even 99%; who knows.

But surely you do not believe that EVERY person is mediocre. The problem I have with the view you have presented (and I mean nothing personal by this) is that you've essentially mandated that everyone dumb themselves down to some arbitrary level. How will the true geniuses ever shine if we require everyone to be of the same brightness?

And no, I don't consider myself to be one of the geniuses who should be excused from the normal policies, I just think that if we allow this kind of thinking to take root, we'll be selling ourselves short (as a company, or country, or species, take your pick) of what we could otherwise achieve.

Sure, that will make it harder as the number of people increases (as you have a tougher time picking out the true geniuses from the rest), but I do not think we should be using "finding real talent is hard" as an excuse to make "just enforce mediocrity" our policy.

Re:One person's myth is another person's fact. (1, Informative)

Anonymous Coward | more than 4 years ago | (#30617042)

Well, everyone's welcome to their opinion, but it's pretty well proven after decades of software engineering that code should be commented. The price of maintaining comment-free code is well known.

The frilly article said nothing about not commenting code. It is against silly comments.

There is a school of thought among programmers who consider themselves hotshots that if you are not a hotshot you have no business touching their code. The problem with this attitude is that it has little to do with the real world, where people change jobs and programmers inherit someone else's code. If you want to write perfect, comment free code in your perfect little world, go right ahead, but don't expect to make a living at it most of the time.

I don't want to write comment free code, but I also realize that extensive commenting is stupid and counterproductive. I have seen too many instances of code, where nearly every line of code is commented and most of those comments add absolutely nothing of value -- on the contrary, the comments just make the code more difficult to read and add to the burden of maintenance.

I have also seen too much "if-then-else-switch-for-break-continue" code, where the extensive commenting is a symptom of absolutely awful code. Fix the code and you can at the same time get rid of most of those comments, while still leaving the code more readable than it was before. Generally, if you need more than three levels of indentation, you should really consider for a moment if you could structure the code better. The same thing with ifs, switches and other control structures; if you have a 30 line mess of control structures, you're quite likely doing something wrong and instead of adding to the mess by writing another 30 lines of comments, you should think about ways to make the code simpler (something that might be understandable with a short single comment).

Some people have a stupid notion that the more comments you write the better, but that is simply wrong. Over-extensive commenting can be almost as bad as not commenting at all, because it bloats the code base (more to maintain, since comments must be maintained as well!), makes the code less readable and because it drowns out the really important comments. The important things to comment are functions (especially if you want to generate API doc from the code), loops that aren't obvious (commenting invariants if often a good way to do this), and constraints and gotchas (ie. if there's some API/platform/algorithm imposed limitation or requirement, don't expect the people reading the code to know about it, but tell exactly where the limitation or requirement comes from and what it is!). When you're using some commonly used algorithm, it's also good to mention it, since it really helps "getting into" the code, if you know what to expect.

Re:One person's myth is another person's fact. (2, Interesting)

b4dc0d3r (1268512) | more than 4 years ago | (#30617174)

My opinion is you're a stubborn idiot.

Allow me to explain. I'd love to see some concrete evidence that commenting is "pretty well proven" as well as a quantified "price of maintaining comment-free code" which you think is "well-known." The very existence of this post, and all of its replies, suggests differently. This has been argued on both sides since the idea of comments first came up. Sure there are commando style morons who refuse to type one comment, just like there were countless commandos who optimized by bypassing the operating system and going directly to the BIOS in the early days. There always will be.

After decades of software engineering, we moved from spaghetti coded ASM to readable C to object-oriented, class-based programming. Lessons learned early on don't necessarily apply. In fact, the higher level the language, the less documentation seems to be required. If data-hiding is always enforced, there are page after page of code which require absolutely zero comments because they are just get/set methods. The odd "setting this has side effects, which is why we do it this way" is an exception, not the rule.

The real exception is when you get into complicated event-driven models supported by objects. It's sometimes impossible to tell, looking at your single file where you need to make a change, which object uses this feature, or which event ultimately triggers this method. I've read some of that code, Java being my favorite example, and it's usually very difficult to see where something gets kicked off. Usually I solve it by making a breakpoint and checking the stack trace - but you can't require that someone reading your code have a working dev environment they can just open the code into and start debugging - it has to be understandable while being read, not executed. That stuff needs documentation - but it might be better done in external tech design type docs, not inline.

Very few programmers are of the hotshot variety - you might be misinterpreting a little. If I build a bridge and someone tears it down and builds a functionally equivalent version, I tend to take it personally. I'm no hotshot and I don't think that person should stay away from my perfect code, but it's something I created being thrown away or altered for no apparent reason. "[I]f you are not a hotshot you have no business touching [my] code" has little to do with the real world because it is rarely seen in the real world. No one gets permanent ownership of a file or block of code, and if you run your ship that way it's your own fault. Set up the environment so that's not even possible. Cross-training someone to be your backup is a relatively common thing to do, and eliminates the possibility of having that hotshot, so if he/she exists, it's management's fault for either enabling or not firing that employee.

Throwing away code because it's "not maintainable" simply due to lack of comments is laughable. Worse than laughable, it's cryable. Requiring that everything be commented so you can put a check mark in the "my team always comments their code" box makes you sound like the coder's worst nightmare. Creating work for no reason is absurd, but it allows management to claim they are understaffed and need a bigger team. That's the way management promotes itself, seems like - require a bigger team, then use that to show you can handle a bigger team, and it keeps growing because you have people 25% dedicated to commenting code. You're completely missing the point.

We have had requirements as a result of ISO 9001 and CMM qualification which were just as blind as you are, and as a result have code which does not match the comments at all. The functionality is clear based on context, but in the rush to get a feature out by a client commitment date (that is not within our control) sometimes these things get overlooked. It is far better to reserve comments for when they are needed. And if they are not needed, they should not exist. You want a theoretical team which updates comments along with the code, and all peer reviews catch any outstanding comments, your costs are going to skyrocket. The real world requires lots of time to ensure documentation stays up to date, and your focus should be primarily on anything used by external users, second on internal documentation like design or event mapping, and last on code. If you have time and money left.

Comments like "yeah, I don't like this either" or "hack, to be fixed later" indicate your team didn't have enough time to do it the right way the first time. It's a warning to whomever makes changes later that something is amiss. If the coder knew what to comment which might be helpful, they'd probably go ahead and implement it. Perhaps you'd like to see "optimize this" or "I have to stop working on this so I can finish my commenting before peer review so we can meet the deadline." It's also a warning that your team needs to put everything down and go read other people's source code. If you know how other people write code, you might agree or not with the way it was done, but it certainly opens you up to new ways of doing things. It also makes it easier to read uncommented code, or well-commented code for that matter.

Something as simple as looping through an array and doing something with the data barely requires a comment - anyone maintaining the code should have an idea how loops should work. If you do something like start at index 1 of a zero-based array, that requires explanation. Otherwise, these things are obvious or you shouldn't be paying the maintainer.

It's clear you will play the bureaucrat, requiring all red tape to be completed in triplicate before one may use the stapler. You will never pay me because I will never work for you. If you're going to manage people, you have to understand how they work, and even if you think you do, even if you were once in that position, it's obvious you either forgot or learned in a different era.

Think about this for a while. Every compiled application out there is completely documented. You can disassemble anything and figure out how it works. If your coders have that mentality, hints like variable and function names, indentation, and clearly indicated array access are a luxury. If your coders are not thinking this way, they are write-only monkeys and deserve no employment.

You might think I don't comment my code, but I very much do. If you see a comment in my code, it's because it's IMPORTANT, not because it's REQUIRED. The IMPORTANT stuff gets buried in the noise of what's REQUIRED, and no one can tell a difference.

You have a low user id, and your journal consists of complaining about slashdot moderation. I'm guessing you're old, having moved from coding long ago to managing a team, and maybe past that. You have little tolerance, despite what you claim in some of your other comments, and like to have things your way because that's what makes sense to you. Imposing your methodology on others isn't the best way to get things done - understanding why people do things the way they do, why their system makes sense to them, is. What you're suggesting is an absolutist solution in which there is no "why", no reason or rationale, it's "just because." That has no place in the real world, and maybe neither do people like you.

No Comment (5, Funny)

Anonymous Coward | more than 4 years ago | (#30616700)

No Comment

Re:No Comment (0)

Anonymous Coward | more than 4 years ago | (#30616718)

Microsoft is a great example of why commenting code is a good idea

Cliche, but true... (5, Insightful)

Xaroth (67516) | more than 4 years ago | (#30616716)

Clean code tells you how, good comments tell you why.

Fixing the "how" becomes significantly easier when you know "why" the code was there in the first place.

Re:Cliche, but true... (1, Insightful)

Anonymous Coward | more than 4 years ago | (#30616758)

This is absolutely true and even how becomes more important with lower-level languages where the code probably will not imply the intended outcome. Try figuring out clever assembly code without a running commentary; it's not fun.

Re:Cliche, but true... (2, Insightful)

Brian Feldman (350) | more than 4 years ago | (#30616850)

Clean code tells you how, good comments tell you why.

Fixing the "how" becomes significantly easier when you know "why" the code was there in the first place.

You seem to be implying here that good comments cannot explain how something non-obvious works. Often in software there are tricky sections of code that benefit from both comments explaining why a given algorithm is implemented but also how the control flow works. Comments are also extremely useful to mark spots that need attention later but are sufficient for now, and also to document any type of "contract" that a particular body of code adheres to.

Re:Cliche, but true... (1)

Nerdfest (867930) | more than 4 years ago | (#30616912)

In most high level languages, description method or function names tell you why as well.

Re:Cliche, but true... (1)

PakProtector (115173) | more than 4 years ago | (#30617054)

C is a high level language. Anything more complex is balderdash and chicanery.

Re:Cliche, but true... (3, Insightful)

Wraithlyn (133796) | more than 4 years ago | (#30616896)

Indeed, and perhaps it's an obvious point but I'd also add that clean code should also tell you "what".

Whenever I have a block of code whose purpose seems unclear, I try to put it into a function whose name clearly describes what it does. This immediately makes it more understandable, and reusable to boot.

Comments should explain why something is done the way it is, the reasoning behind it. They should not simply label what something IS, that should be the job of good naming practices.

Re:Cliche, but true... (1)

Drethon (1445051) | more than 4 years ago | (#30617166)

Agreed, the problem with many comments is they try to explain how or even what instead of why. Explaining how or particularly what often just duplicates what the code explains to a skilled programmer (this works as long as the code isn't too obscure).

Re:Cliche, but true... (3, Interesting)

BikeHelmet (1437881) | more than 4 years ago | (#30617216)

I don't clutter my code with comments. If there's a comment, it's a really important gotcha, or something that doesn't make sense but has to be left for legacy reasons.

And I write a detailed description at the top of every file. Not just what a class does, but also why. Why some of the methods do what they do, and other places they might get used that might need to be changed.

Nothing annoys me more than...

/* Method name: Foo
Returns: int Bar
*/
public int Foo()
{
return Bar;
}

When a comment could be run through a preprocessor to turn it into the actual code, the comment is saying too much, and should be removed, simplified, or changed.

Over documentation is good (1)

nurb432 (527695) | more than 4 years ago | (#30616722)

Remember what is crystal clear to you may not be to the guy coming in to clean your mess up in a few years. ( or even yourself as you have learned more and advanced your skills, and have to go back, often with a 'wtf was i doing'.. )

Having to decode your thought processes places extra a burden on the 'next generation'

Re:Over documentation is good (5, Interesting)

fdrebin (846000) | more than 4 years ago | (#30616744)

Remember what is crystal clear to you may not be to the guy coming in to clean your mess up in a few years. ( or even yourself as you have learned more and advanced your skills, and have to go back, often with a 'wtf was i doing'.. )

I worked on the same system for 15 years. More than once I saw some code and said "what idiot wrote this!?" ... only to realize it was me, 5 years ago. Yes, that did indeed lead to me becoming a) much less prone to "clever tricks" and b) much much better at explaining what (WHY) I was doing whatever it was.

Re:Over documentation is good (0)

Anonymous Coward | more than 4 years ago | (#30616796)

God yes....

A system I work with now has 29 serial links (modbus) to various places... the links and bus registers etc in external devices are ONLY documented in the header files of the C code used on embedded controllers...

Trying to now virtualize this fecking mess is a major pain in the ass as we have to sit digging through header files and make maps of registers in use by hand... By hand because the code format is not at all consistent, neither is naming convention...
Writing a parser turned out to be a waste of time since the header format will never be used again. *sigh*

Kill me....

Oh, and the code has been updated but not the comments so you have gems like
a = 30913; // register 40914

etc... kill meeeeee

Re:Over documentation is good (2, Insightful)

jocabergs (1688456) | more than 4 years ago | (#30617004)

I think over documentation isn't on the whole a bad thing, but there have been a few times where I've been more confused by the comments than the code. I don't care if people get clever with code and have clear comments, but I hate when people try to have clever comments, comments are not supposed to be hard to understand.

Wrong on all accounts (5, Insightful)

smartin (942) | more than 4 years ago | (#30616728)

Having worked as a programmer for many years, all I can say is poorly commented and undocumented code is unprofessional and I would rather
rewrite it than try to decipher it. I've heard all of these excuses before and all I can say to the people that make them is: Your code is not as
good as you think it is.

Re:Wrong on all accounts (1, Informative)

MichaelSmith (789609) | more than 4 years ago | (#30616808)

I would rather
rewrite it than try to decipher it.

In the environment I work somebody will try to import your change later and they will want to know why you made that change. They aren't going to be very impressed if your answer is that you couldn't understand the original code. By making that change you would be creating work for a lot of other people down the chain.

Re:Wrong on all accounts (0)

Anonymous Coward | more than 4 years ago | (#30616908)

They can suck my sweaty balls.

Some asshat believes he is too good to comment his code? I don't have the time to waste deciphering his spaghetti rats nest of global variables and copy/paste flow control.

Re:Wrong on all accounts (0)

Anonymous Coward | more than 4 years ago | (#30616964)

Job security

Re:Wrong on all accounts (3, Interesting)

CAIMLAS (41445) | more than 4 years ago | (#30616810)

What bothers me is not so much undocumented code, but undocumented functions and/or blocks of code. Main should be well documented, and a function should have a line or two explaining its function, but unless its particularly obtuse code, I don't want/need documentation.

Re:Wrong on all accounts (5, Insightful)

TheRaven64 (641858) | more than 4 years ago | (#30616832)

Your code is not as good as you think it is

Even if it is, the person reading it might not be as good a developer as you, or may be as good (or better) but with different experiences. In both cases, they may not be able to read and understand your good code without comments. When they change it and it breaks as a result, then it's your fault.

Re:Wrong on all accounts (4, Informative)

tomhath (637240) | more than 4 years ago | (#30616846)

Wrong on all accounts

RTFA, the article starts out with these two sentences:

It seems to me getting good at writing comments is an under-appreciated part of a Programmer's development. However, I feel that this is a part of programming that's almost as important as writing code itself.

His point is that worthless comments are worse than no comments at all. Unfortunately a large percentage of the comments you see in code today were autogenerated by the IDE and are just noise.

Re:Wrong on all accounts (2, Interesting)

SerpentMage (13390) | more than 4 years ago | (#30616880)

And therein lies the problem.

There are two major problems:

1) As much as I would like to say that documentation helps, I actually don't think it helps unless you writing an API. But even then I wonder. The real problem with documentation is that as much as we would like to keep it up to date, it does not happen. I personally would prefer modular code that works without tricks than code with comments and tricks.

2) The problem with comments is that it fails the psychological test. When I write something down it does not necessarily mean that another programmer is going to understand what I mean. The reason has to do with the words I choose and how I phrase things. Even with good wording I can't explain a complex system. For example, let's say that I had to explain some complex multi-threading code. Unless the third party had a level of knowledge as good as mine it will not matter what I write as a comment since they lack the basic threading knowledge. And this lack knowledge is a key problem in any complex system.

Thus if I had to choose between comments and simplicity I choose simplicity since one can understand simplicity.

Re:Wrong on all accounts (2, Insightful)

Nerdfest (867930) | more than 4 years ago | (#30616976)

You shouldn't need to decipher the code. Most of the problem is not the missing documentation, but the poorly written code.

Re:Wrong on all accounts (3, Interesting)

Nerdfest (867930) | more than 4 years ago | (#30616982)

.. and also, you are correct. With code that needs to be deciphered, you're generally better off re-writing it.

Has No One Actually Studied This? (4, Insightful)

Greg Hullender (621024) | more than 4 years ago | (#30616762)

In thirty years of programming, I've heard one person after another argue about how to comment and how much to comment, but what I've never seen is any kind of serious study attempting to measure what actually works best. I personally like to make comments paragraphs, not lines, and generally end up with code that's 1/3 to 1/2 comment lines, but the most I can claim is "it works for me."

I do think good commenting has to be a key part of software engineering (when it finally becomes a real engineering discipline), and I know software engineering is a hot topic these days, so perhaps there's a paper on this that I just haven't seen yet. If not, someone really ought to do a serious study. And then start teaching people something that's actually known to work.

--Greg

Re:Has No One Actually Studied This? (0)

Anonymous Coward | more than 4 years ago | (#30616826)

Bonus points to the people who write their comments in clear grammatically correct prose.

Re:Has No One Actually Studied This? (1, Funny)

Anonymous Coward | more than 4 years ago | (#30616854)

In thirty years of programming, I've heard one person after another argue about how to comment and how much to comment, but what I've never seen is any kind of serious study attempting to measure what actually works best.

// TODO: Implement mathematically optimal commenting

Re:Has No One Actually Studied This? (5, Insightful)

tomhath (637240) | more than 4 years ago | (#30616962)

A former employer (a very big multinational corporation) did a study that tried to correlate the number of comments in code to the number of problem reports against it. Not surprising to me, they found that in general the more comments in the code, the more problems were reported against it. That was my observation as well; bad programmers couldn't figure out a straightforward solution to a problem so they wrote messy code with lots of comments trying to explain what they were doing. The really good programmers wrote simple clean code that only needed a few comments.

Another characteristic of bad programmers that I noticed was their tendency to keep copying data from one data structure to another instead of using it in place. Obviously an indication of bad design, and it introduced lots of bugs. You knew as soon as you opened a source file and saw comments like "Copy blah-blah data from abc array to xyz array" that you were in trouble.

Or (3, Insightful)

MichaelSmith (789609) | more than 4 years ago | (#30617116)

The code which is business critical and necessarily complex gets commented a lot as a mitigation measure. But it still has problems, often because the business requirements change a lot or are poorly defined.

Commenting "why" (2, Informative)

Chris Newton (1711450) | more than 4 years ago | (#30617060)

I've heard one person after another argue about how to comment and how much to comment, but what I've never seen is any kind of serious study attempting to measure what actually works best.

FWIW, in studies of the problems developers encounter in practice, one recurring difficulty is working out the motivation behind a given piece of code. This supports advice to comment why the code is written the way it is. See, for example:

  • LaToza, Thomas D., et al, Maintaining Mental Models: A Study of Developer Work Habits, in ICSE '06: Proceedings of the 28th international conference on Software Engineering
  • Ko, Andrew J., et al, Information Needs in Collocated Software Development Teams, in ICSE '07: Proceedings of the 29th international conference on Software Engineering

Both papers were coauthored by Robert DeLine and Gina Venolia of Microsoft Research.

In LaToza, 66% agreed that "understanding the rationale behind a piece of code" was a serious problem for them.

In Ko, "Why was the code implemented this way?" was the second most frequently unsatisfied information need among the developers observed.

More verbose == less readable? (4, Insightful)

nmb3000 (741169) | more than 4 years ago | (#30616770)

I disagree with this general statement:

For instance, would you rather use a one-liner that requires a 3-line comment, or a 10-liner that requires no comments? In most cases, code's readability suffers more when it's overly verbose than when it has a high comment to code ratio. Thus, I would choose to write the comment in most cases.

First, I think any time you consider writing some clever one-liner in real production code you should rethink long and hard. Is the hypothetical 6 fewer lines of code really worth it? Unless you're doing it for absolutely required performance reasons, the 6 lines of code you save won't buy you anything but the wrath of whoever has to come along in 3 years and refactor your code.

Of course you can be too verbose, but it's a much rarer problem than the alternative. Even overly verbose code is usually easier to understand, easier to maintain, and easier to refactor than that clever little one-liner. And if you're that worried about a verbose section of code, extract a method, give it a good name, and be done. Now you have both a one-liner method call that is easy to read in context and a more verbose implementation that is easier to understand and maintain in the future.

Re:More verbose == less readable? (1)

mpc92 (302291) | more than 4 years ago | (#30616954)

I find over and over that I'd rather have 10 simple lines over 1 tricky line for one simple reason: invariably one of the tricky actions holds the key to a bug, and I want to have more precise control over where my breakpoint is (which method call in the tricky line is throwing that null reference exception anyhow?).

Re:More verbose == less readable? (1)

buddyglass (925859) | more than 4 years ago | (#30617014)

And if you're that worried about a verbose section of code, extract a method, give it a good name, and be done.

In total agreement here. Usually just look at a short-ish method's name, its parameters, and its return value, makes it clear what it does. This is different than if that same code were included in-place, since in that situation its not clear what the "inputs" and "outputs". Plus extracting it usually makes the section from which it was extracted easier to read.

Less verbose is more writeable (3, Insightful)

Anonymous Coward | more than 4 years ago | (#30617056)

Early COBOL and Fortran computation code proves you wrong here. COBOL, without COMPUTE, required a separate line for each operation. Fortran from the start showed simple algebraic equations.

COBOL
======
MULTIPLY B BY B GIVING B-SQUARED.
MULTIPLY A BY C GIVING A-C.
MULTIPLY A-C BY 4 GIVING A-C-4.
MULTIPLY A BY 2 GIVING A-2.
SUBTRACT A-C-4 FROM B-SQUARED GIVING DISCR.
CALL SQRT USING DISCR GIVING RT-DISCR.
SUBTRACT B FROM RT-DISCR.
DIVIDE RT-DISCR BY A-2 GIVING ROOT-1.

Fortran
=====
R1 = (-B + SQRT(B**2 - 4*A*C))/(2*A)

Do you want 8 lines of code to write out the quadradic formula? Is that any clearer than one line? A simple one-line comment explains what *root-1* means to the program as a whole.

I've seen people write out intermediate variables like that using PHP or Python. Both languages handle that for you.

Re:More verbose == less readable? (1)

pjt33 (739471) | more than 4 years ago | (#30617140)

Unless you're doing it for absolutely required performance reasons

Or numerical reasons. Sometimes it happens that the 3-line version is algebraically equivalent to the 10-line version, but more stable numerically. In this case you may need to replace 3 lines of comments with 20 lines sketching the outline of the 10-line version and giving a proof of correctness of the 3-line version.

In other news... (4, Insightful)

CAIMLAS (41445) | more than 4 years ago | (#30616776)

In other news, people have personal preferences, just as they do in the literary world. Some people like Ayn Rand, others hate her. Some like Stephen King, others hate him. Not so much their stories, but their writing styles.

Snowcrash is an awesome story; one many can appreciate, but most people couldn't get through his writing style to finish the book.

I think that if more people wrote code (or, for that matter, books) like George Orwell wrote his books, code (and books) would be generally more readable: shorter sentences (lines of code) which convey a single meaning (function), strung together into short paragraphs (code blocks), chained together into a larger cohesive whole.

Re:In other news... (1)

mewshi_nya (1394329) | more than 4 years ago | (#30616830)

sentences linked into a meaning into a paragraph into a story! Brilliant!

Actually, I really like this post. Someone, please mod this up.

If more people wrote simpler code, it would be easier to read on my end, as a non-programmer

Re:In other news... (0)

Anonymous Coward | more than 4 years ago | (#30617022)

undocumented code is unprofessional.

unprofessionals dont get hired often or keep their jobs for long.

if you work for me, you document your code, cause unless specifically agreed to beforehand, your code is part of a product belonging to my company, and i will not be screwed over down the road cause you left, and the code is nigh undecipherable except by the one who wrote it.

Re:Shorter sentences (1)

paylett (553168) | more than 4 years ago | (#30617126)

I think that if more people wrote code (or, for that matter, books) like George Orwell wrote his books, code (and books) would be generally more readable: shorter sentences (lines of code) which convey a single meaning (function), strung together into short paragraphs (code blocks), chained together into a larger cohesive whole.

Complexity of that last sentence:
* 52 words,
* 17 punctuation characters,
* 5 parentheses blocks,
* at least half a dozen ideas.

But I'm just having fun. I agree with you 100%.

Blame my professor (1)

Quila (201335) | more than 4 years ago | (#30616804)

I had excessive commenting drilled into me in college. It's one of the things I've had to unlearn.

Comments are not design (1, Insightful)

Anonymous Coward | more than 4 years ago | (#30616820)

Code that has concise, sensible comments is indicative of a good design. However, I don't care how 1337 you are, no professional developer worth a damn programs anything bigger than a 3-line batch without at least some sort of design document. Comments that relate back to the design document are one thing, but it is really hard to use comments to point out the design of a program which had no design other than "I am ok to just wing this because i am 1337."

Please no (5, Insightful)

dachshund (300733) | more than 4 years ago | (#30616836)

Christ, I know everyone has their own personal style and everything, but this is just pernicious. In any case, the author gives the game away: when he thinks code is overcommented, he can ask Emacs to hide the comments. So far as I know there's no automatic system that will generate the comments that the author failed to put in because the code was "self-documenting". This is particularly important when you're working with anything other than standard libraries --- you might know what "libfzp_inc_param_count_fast", but your reader probably won't.

Right now I'm working on a crypto library that incorporates a lot of very specific elliptic curve operations. My technique is to comment the hell out of every damned interesting piece of code on the assumption that a picky reader can turn off the damned comments if they get in his way. In fact, there are various places where I've actually scaffolded all of the comments before writing a line of code. Doing otherwise would have been an enormous headache and made bugs a whole lot more likely. And this way even a non-expert should be able to understand the entire program flow.

Unfortunately, one of the previous pieces of software in this area followed the poster's "self documenting code" style (very nice, clean, well written code with no comments), and even I find it difficult to piece together what's going on in places --- not because all of the code is crypto-specific, but because the author has thrown so much effort into writing "clean, pretty" code that it's actually hard to know where the crucial pieces are. I can't quite explain why I find this so irritating, but perhaps some of you will know what I mean.

Re:Please no (1)

MichaelSmith (789609) | more than 4 years ago | (#30616946)

Christ, I know everyone has their own personal style and everything, but this is just pernicious. In any case, the author gives the game away: when he thinks code is overcommented, he can ask Emacs to hide the comments. So far as I know there's no automatic system that will generate the comments that the author failed to put in because the code was "self-documenting".

Yeah there is this guy I have the misfortune to be working with. Once in a code review he insisted that all my code be double spaced (one blank line between every line) because he was having trouble reading it. I said why don't you configure your editor accordingly. He said in his team they do pair programming so every workstation has to be set up exactly the same way...

Re:Please no (1)

gnasher719 (869701) | more than 4 years ago | (#30617088)

Yeah there is this guy I have the misfortune to be working with. Once in a code review he insisted that all my code be double spaced (one blank line between every line) because he was having trouble reading it. I said why don't you configure your editor accordingly. He said in his team they do pair programming so every workstation has to be set up exactly the same way...

The guy is completely illogical. Next you review some of his code, and you insist that all his code should be single spaced (no blank lines between lines of code) because you have trouble understanding the code if it doesn't fit on a single screen. What is he going to do then?

Re:Please no (0)

Anonymous Coward | more than 4 years ago | (#30617206)

This attitude is the same as the original post. 'my code is perfect and every should conform to what I do if you do not like it here are some hoops to jump thru to be like me'. The guy asked you to match what the rest of the team was doing and you came back with a snide remark. Instead of showing him why that style is 'worse'/'better'.

The reason for doing these things is not always for yourself. It is for other people to help you out. Your not as good as you think you are. You are also not always around or will be around. I have dealt with programmers such as you many times. MANY times everyone else ends up fixing the mess you make. Then you turn around thinking they are all full of crap.

I am a pretty good programmer. However, *THE* highest complement I ever get from other programmers is 'your code is easy to read and the comments are always spot on.' When writing code you are writing for 3 groups. 1) the compiler 2) yourself and 3) most important your team mates.

For 1 you could write cryptic ass crap and the computer would figure it out.
For 2 you could also write cryptic ass crap and you MIGHT figure out today but what about 2 months from now?
For 3 you can NOT write cryptic ass crap. You *MUST* communicate to them what you are doing. If this means double spacing your code then so be it. BTW after 20 years of coding I have found double spacing is most readable. They help you make your code look good and easier to read. It looks 'funky' at first but you quickly come to like it. When its 2 in the morning and I have to tweak some code I do not want to have to worry about what options *YOU* were using in your editor and making my options match. You will have style fights and you will loose these battles, I have lost/won many. I have worked on projects where everyone did 1 style. Those projects were successful. I have also been on many projects where 'we are all professionals and write however we like' and those all failed. The reason they failed? The team was not a team it was a group of 'hot shots'. One of the first rules of my projects are 'use the style of the group or find another group'. This helps promote teamwork in a weird way. It also helps others quickly find bugs as the code will just 'look weird'. This is one of the most important tools you will to writing 'good' code. Do not throw it away because you think you are 'better' than everyone else.

Re:Please no (1)

The_reformant (777653) | more than 4 years ago | (#30617030)

Unfortunately, one of the previous pieces of software in this area followed the poster's "self documenting code" style (very nice, clean, well written code with no comments), and even I find it difficult to piece together what's going on in places --- not because all of the code is crypto-specific, but because the author has thrown so much effort into writing "clean, pretty" code that it's actually hard to know where the crucial pieces are. I can't quite explain why I find this so irritating, but perhaps some of you will know what I mean.

I can kind of understand this, often in the quest to make things more understandable things are refactered into methods/functions that arent modular operations in themselves which can lead to more confusion since they masquerade as pieces of modularly reusable code when they in fact rely on assumptions which happen to be satisfied by their caller.

Its also worth noting that you do get a performance and memory usage penalty for pushing additional frames onto the stack. In certain cases that can be a factor. (As an aside why is it in Uni that recursive code is held in such high regard as being elegant whereas in day to day like its almost always a bad idea. I made that mistake a few times early on in my professional life).

Re:Please no (1)

farnsworth (558449) | more than 4 years ago | (#30617182)

Christ, I know everyone has their own personal style and everything, but this is just pernicious.

Every is entitled to their own personal style, but context is also very important.

If you are writing a math-heavy algorithm in c, comments are crucial, both at the API level and within the implementation.

On the other hand, if you are writing a webapp in c#, an organizational mandate to "document every public method and public class" can be a huge waste of time if not harmful.

Lies or Wishful Thinking (1)

KalvinB (205500) | more than 4 years ago | (#30616844)

Comments are useful if kept up to date with the code. Otherwise they turn into bald faced lies or wishful thinking.

Code that follows a logical structure, proper use of white-space, well-name variables and methods, etc is far easier to read and debug than code that has a lot of comments. Comments are non-standard and difficult to search for when looking for a problem.

Comments are best reserved for things which are non-trivial to figure out by reading and following the code.

Choice of Language (2, Insightful)

mandelbr0t (1015855) | more than 4 years ago | (#30616856)

It really depends on what language you write your code in. Object-oriented languages in general require less documentation since good design and properly named methods and properties do document things relatively well. Class-level documentation is much more important than documenting the details of the methods themselves. Java and .NET require much less documentation to maintain. I've looked over Java code I wrote years ago, and it still makes perfect sense, even though I've only really documented the API and not the details. Perl and C code, on the other hand, can be unmaintainable even with a number of comments, because the old functional design is not easily maintainable. Consider rewriting these in a more modern language.

Call me a hotshot if you want, but I shouldn't have to assume that the person maintaining my code is a moron, nor that my non-technical manager needs to understand every single statement I wrote. I play nice with QA, and happily write test cases for my code. That's as far as I'm willing to go to ensure that my code quality is good, and that I can leave without the possibility of my code degenerating into the spaghetti-like mess I've had to clean up on a number of occasions. Sure, I don't get hired to write code anymore, but I don't care. Software Engineering and overdocumenting every single tiny intranet project is wasteful. Cleaning up after morons who believe that their engineering background can make up for their lack of talent and experience is aggravating. Answering to them is intolerable. There's other things I can do with my technical background that don't involve butting heads with people who dogmatically apply software engineering methodology to everything they do. It's their loss, not mine.

Re:Choice of Language (1)

Nerdfest (867930) | more than 4 years ago | (#30616898)

Exactly. If you're coding in Assembly, you damn well better comment, but if you're coding in Java, I'd better not need much, if any. Generally, any high level language code in need of a lot of comments should never make it through code review.

I am NOT a coder... but... (1)

GuyFawkes (729054) | more than 4 years ago | (#30616862)

I suspect comments in code are like project notes.

Even when I come back to my own projects a year or so later, it is obvious what I was doing with x widget attached just so the y widget.

It is rarely obvious WHY I came around to that solution.

Project notes, and I suspect good comments in code, address the though processes behind doing something this way, rather than explaining in detail WHAT the code does.

10 REM FOR 16 BIT NMS MACHINES
20 FOR X=1 TO 10
30 PRINT "HELLO"
40 NEXT X

(told you I wasn't a coder)

But line 10, the comment may be very useful, aha, that's why this works on X machine but not X machine, etc.

Does he think comments are pseudocode? (4, Informative)

EsJay (879629) | more than 4 years ago | (#30616868)

When you update the code that the comment references, you usually have to update the comment as well.

If your comments are that detailed, you're doing it wrong.

Re:Does he think comments are pseudocode? (2, Interesting)

presidenteloco (659168) | more than 4 years ago | (#30616988)

Except that a programmer should be able to use (call) your api / public methods without having to read their
implementation. The method signature and comments should be enough.

Therefore, as well as conveying the gist of what the thing/method is and how it fits into its context,
you should also document all significant corner cases or unexpected behaviours of your object/method.

And if you change the implementation in such a way that you falsify one of those comments, without
modifying the comment, thats a fail, and renders your code library low quality in one stroke.

Re:Does he think comments are pseudocode? (1)

Arimus (198136) | more than 4 years ago | (#30617082)

Depends, if you are using doxygen style comments and change the function header then the comment changes...

Re:Does he think comments are pseudocode? (1)

noidentity (188756) | more than 4 years ago | (#30617188)

If your comments are that detailed, you're doing it wrong.

No problem, just add some comments to explain the details.

So who is this guy? (5, Insightful)

anti-NAT (709310) | more than 4 years ago | (#30616872)

No offence intended to him, but he's just re-interating the sort of commentary on commenting that's in Code Complete, The Practice of Programming, Linux kernel CodingStyle etc. He's not offering any original insights, or telling war stories that people can learn from. Any decent programmer would already know these myths, and if they didn't, they really should be reading books such as the ones I've listed, not a blog entry with very little original content.

IOW, what makes special enough to be Slashdot front page news?

Re:So who is this guy? (0)

Anonymous Coward | more than 4 years ago | (#30617012)

slow news day. new here?

Re:So who is this guy? (0)

Anonymous Coward | more than 4 years ago | (#30617120)

IOW, what makes special enough to be Slashdot front page news?

IT'S BOOKS 2.0

Re:So who is this guy? (1)

oogoliegoogolie (635356) | more than 4 years ago | (#30617196)

I have no idea who this guy is either. Can someone fill us in?

Compare / contrast. (1)

fahrbot-bot (874524) | more than 4 years ago | (#30616884)

...would you rather use a one-liner that requires a 3-line comment, or a 10-liner that requires no comments...

Depends on the efficiency and maintainability. A one-liner that's "perfect" is probably worth the extra comments. Ten lines of self-evident code may not be better. Personally, I can't stand code that starts "boolean done = false; while (!done) {...}" when the condition can be determined inline using an operational variable.

"would you rather use a one-liner" (4, Insightful)

lax-goalie (730970) | more than 4 years ago | (#30616920)

would you rather use a one-liner that requires a 3-line comment, or a 10-liner that requires no comments?

Easy. 10 lines, no comments. After writing a couple of million lines of code, the more code I write, the more I unwind it. Somewhere along the line, adolescent programmers got the idea that jamming all your logic into as few unreadable lines as possible is the fastest way to manliness. Way, way wrong.

Modern compilers and interpreters do a pretty good job nowadays. Source code bytes are near free. If you have to skull out dense code 6 months after you've written it, you're doing something wrong.

(OK, Lisp and APL are special cases, but really, when's the last time you wrote Lisp or APL, other than for fun?)

every line of code should be commented (5, Funny)

caywen (942955) | more than 4 years ago | (#30616932)

Every line should be commented, like: // Declare function called doit with one int param that returns an int
int doit(int i) // See above comment
{ // The function's open brace. I like to put braces on their own line. You should too!! BTW, this is C code, so braces are totally the way to go.
      if(i == 0) // Check if i is 0. You know, in C, "==" is the way to compare values, unlike in VB where you use a single "=". Just thought u should know.
            return 0; // Return 0. That is, all the bits of the return value are 0. We could also return i, because i is 0, too. That is, all the bits of i are 0. On a 32 bit system, there would be, like, 32 0's.
      else
      { // Begin an if block using a brace (this is C syntax!!!)
            int j = i - 1; // Declare an int variable named j that is one less than i
            return i + doit(j); // Return the sum of i and the value of calling doit with j
      } // Finish the if block with a C close brace. By the way, we could have written the above code as return i + doit(i - 1) without using the braces.
} // The function's close brace.

There! Now that is both way readable and informative. Anything less would just not pass my code review.

Re:every line of code should be commented (1)

mandelbr0t (1015855) | more than 4 years ago | (#30617124)

Parent marked troll? I think it's very funny.

Not commenting is a sign of not thinking or caring (3, Insightful)

presidenteloco (659168) | more than 4 years ago | (#30616936)

If you don't header-comment your class or public method,
I have to conclude that you cannot articulate what it is or what it
means or is for. So probably the code is incoherent/inconsistent too.

So that's going to make me write my own instead of using your code.

Or maybe you can articulate what it is about but are borderline
autistic and don't see the need to communicate meaning to others.
To me this just means you are so inexperienced in programming that
you a) don't understand the costs of maintenance, and
b) don't even realize that you yourself aren't going to be able to figure
out your code in six months.
Either way, I'm not using that code if I can help it.

Should be... (1)

Restil (31903) | more than 4 years ago | (#30616958)

myths about excessive code comments. Provide comments in places where the comment might be useful. If you have some obscure function, the purpose of which might be confusing if you or someone else looks at it a year later, then you need a comment. The more obscure or terse, the more detailed the comment should be. On the other hand, if the function's purpose is obvious just by glancing at it, or the function name is sufficient to describe the entire purpose of the function, there's probably not a need for any comments at all.

Within a function, if you only have nested loops one deep, there's probably no need to comment each closing bracket. But if you have some horrendous 12 dimensional loop with lots of if statements, it might save a few headaches to know exactly which bracket lines up with which routine.
It's just a matter of commenting what is necessary, and avoiding it when it's not.

-Restil

Employment prospects (1)

paylett (553168) | more than 4 years ago | (#30617038)

This, in an age when prospective employers are known to check out candidates blogs. Entertaining.

Strongly RESTRICT Code Commenting (2, Insightful)

omb (759389) | more than 4 years ago | (#30617052)

There are just 3 good reasons for comments in code: (a) to refer to a published paper describing an (obscure) algorithm, eg '[fast graph traversal algorithm, M. M. Balakrishnarajan and P. Venuvanalingam ,Computers & Chemistry, Volume 19, Issue 2, June 1995, Pages 101-106] , (b) to indicate an arcane, obscure usage, which would be better eliminated, but sometimes cannot be eg in device drivers, when merely addressing a device register has side effects, (c) to very briefly document major parts of program flow-meaning, if this isn't otherwise obvious.

In addition, temporary development comments help while writing or refactoring code, but they come out and become empty or (a)-(c), eg // XXXX I dont understand this; or # Class is defined in Foo.pm.

Usually code is OVER commented, or the comments are facile eg 'i++; // increment i' and this CRAP should be avoided at all costs.

The other thing to be avoided is lengthy legalese or copyright information spread all over code. If this is necessary, at all, it should fit on one line and if necessary reference a COPYRIGHT or LEGAL file

OK // Copyright (c) 2001-2010 Foo.Bar, all rights reserved, Licenced under the MIT license.

BAD /* Error constants. Linux specific version.

-- 15 lines deleted

      02111-1307 USA. */

Finally, never believe the comments, at minimum they didnt get debugged!

I can answer that one! (1)

Zero__Kelvin (151819) | more than 4 years ago | (#30617072)

"This is about as close to being a canonical "bad comment ", and yet people who should know better still do it. Why? Because they feel that they should document every function or class. The reality is that documenting something that needs no documentation is universally a bad idea."

The reality is people might know more than you, and you are assuming that you are an uber-programmer when you are not! Maybe the programmer is more qualified than you to write Python (the language the example is in in TFA) and uses pylint. Maybe he doesn't want to sift through 272 warning messages to see which are important and which are superfluous, so he is consistent. Maybe consistency is a good thing in the software domain. Maybe he also wants every member method to be consistintly documented since docstrings are tied in memory to the object and available via help(object).

I am encouraged by most of the comments about comments here on Slashdot thus far. Most people seem to get why comments are a good thing. The author doesn't write them off completely of course, but he is not qualified to write this article either. There is just too much he doesn't yet understand, and he would do well to ask these questions of a qualified software engineer rather than posing them as rhetorical, since in a lot of cases he doesn't know the answers but mistakenly thinks he does, as I have shown.

There is a reason why language designers pretty much universally include a comment mechanism, and why that mechanism has been trending toward the docstring / formal approach away from the "willy nilly" techniques of old rather than removing the ability to comment completely.

Useful comment: (1)

Albert Sandberg (315235) | more than 4 years ago | (#30617108)

// Message below is written by an idiot, jsyk

This guy is WRONG. (1)

sootman (158191) | more than 4 years ago | (#30617110)

"documenting something that needs no documentation is universally a bad idea"

-- yeah, because everyone in the world has the exact same experience and knowledge, so something that's obvious to one person is obvious to the rest of the world and vice-versa. And nobody ever changes, learns new things, or uses things that are obvious now but will be completely forgotten after five years of not using that particular construct.

This guy's opinions are worth less than the comments he eschews.

compares to all professions (4, Insightful)

DaveGod (703167) | more than 4 years ago | (#30617158)

Working in accountancy (and doubly-so for audit) a well-commented file is absolutely necessary. Like (I suspect) computer code, the file should stand on it's own - a competent fellow professional should be able to fully understand it and be comfortable reaching the same conclusions. This is not only good practice for the benefit of your firm but a professional requirement: my institute comes along every few years, selects a few files and basically if they have difficulty understanding the file (or worse, reached different conclusions) then you're in a lot of trouble.

Many of the points in TFA hold up well however - explaining things unnecessarily merely adds bloat, irritates and wastes the time of the reader by telling them obvious, patronising or pointless things. And yes, a perfect accounts job doesn't require any explanation because the schedules will be self-explanatory.

The thing is though, if you're doing anything complex (earning your salary), have to make corrections (hackjobs) or judgements then you need explanations. Manager's will be reviewing your work and you or a colleague will be referring to it next year. If explanations go out of date, update them - if they had value before then value is there in updating them. Yes there is a cost, so there is a tradeoff vs their value to the file. The key is competent fellow professional. Assume your colleague will be reviewing your work and be satisfied that they will be able to understand and appreciate it.

If you're just churning out "stuff that works" then you're at best a technician.

The flipside (2, Interesting)

BigBadBus (653823) | more than 4 years ago | (#30617190)

I used to work for a company [paullee.com] that didn't believe in commenting code...took ages to reverse engineer the code...

Knuth (1)

SEWilco (27983) | more than 4 years ago | (#30617192)

I believe that Knuth had volumes to say about code and documentation.

Don't listen to this crap (2)

MacGyver2210 (1053110) | more than 4 years ago | (#30617218)

FTA: "If anything, comments make code less readable. Nine times out of ten, I ignore comments unless I'm stumped. In fact, I'm tempted to make emacs hide all comments unless I explicitly expand them."

I stopped reading at this point, because the author is clearly a terrible programmer and not someone I want to take coding/commenting advice from. If you do comments right, which this guy clearly doesn't, they can save your ass repeatedly and avoid having to go to deeper, harder-to-reach documentation to make it work. Clearly not someone with any real programming experience behind this 'article' (although it looks more like a twitter feed).

Load More Comments
Slashdot Login

Need an Account?

Forgot your password?

Submission Text Formatting Tips

We support a small subset of HTML, namely these tags:

  • b
  • i
  • p
  • br
  • a
  • ol
  • ul
  • li
  • dl
  • dt
  • dd
  • em
  • strong
  • tt
  • blockquote
  • div
  • quote
  • ecode

"ecode" can be used for code snippets, for example:

<ecode>    while(1) { do_something(); } </ecode>