11

Possible Duplicate:
Is it possible to write good and understandable code without any comments?

When coding often I hear that if comments are needed then it means that the code is too hard to understand. I agree that code should be readable but often the language itself makes the code hard to follow, because of "plumbing" and strange syntax. The languages I use most often are:

Java Mootools Ruby Erlang

Any tips would be appreciated? Thanks

Community
  • 1
  • 1
yazz.com
  • 57,320
  • 66
  • 234
  • 385
  • 1
    Duplicate: http://stackoverflow.com/questions/784250/is-it-possible-to-write-good-and-understandable-code-without-any-comments – tangens Feb 13 '10 at 12:37
  • 3
    Note that code can not tell you WHY something is done in a particular way, only HOW. – Thorbjørn Ravn Andersen Feb 13 '10 at 14:26
  • 2
    It's a myth that only comments can tell "why". Sometimes you do need a comment for that, but often the code can tell the whole story. Look, a comment isn't bad. But consider the need for comments to be a signal that the code could, perhaps, be made clearer. – Wayne Conrad Feb 13 '10 at 14:31

7 Answers7

26

Recommended reading: Clean Code by Robert C. Martin.

In brief, you should

  • use meaningful variable/method/class names,
  • keep your functions/methods short,
  • have each class and method do only one thing,
  • have the code in each method be on the same level of abstraction.

Don't fear of extracting even moderately complex expressions from if statements; which one is clearer to read, this

if (i >= 0 && (v.size() < u || d == e)) ...

or

if (foundNewLocalMaximum()) ...

(Don't try to find any meaning in the first code snippet, I just made it up :-)

Comments in clean code are almost never needed. The only exceptions I can think of is if you are using some obscure language feature (e.g. C++ template metaprogramming) or algorithm, and you give a reference to the source of the method/algorithm and its implementation details in a comment.

The main reason why any other kind of comments is not very useful in the long run is that code changes, and comments tend to not be updated alongside the changes in the corresponding code. So after a while the comment is not simply useless, but it is misleading: it tells you something (implementation notes, reasoning about design choices, bug fixes etc.) which refers to a version of the code which is long gone, and you have no idea whether it is relevant anymore for the current version of the code.

Another reason why I think that "why I chose this solution" is most often not worth documenting in the code, is that the brief version of such a comment would almost always be like either "because I think this is the best way", or a reference to e.g. "The C++ Programming Language, ch. 5.2.1", and the long version would be a three-page essay. I think that an experienced programmer most often sees and understands why the code is written like this without much explanation, and a beginner may not understand even the explanation itself - it's not worth trying to cover everyone.

Last but not least, IMO unit tests are almost always a better way of documentation than code comments: your unit tests do document your understanding, assumptions and reasoning about the code quite efficiently, moreover you are automatically reminded to keep them in sync with the code whenever you break them (well, provided you actually run them with your build...).

Péter Török
  • 114,404
  • 31
  • 268
  • 329
  • 1
    I definitely agree that comments often get neglected when code changes. Good point! – yazz.com Feb 13 '10 at 12:47
  • You should guarantee comments are updated by using code reviews or pair programming. – MarkJ Feb 13 '10 at 13:00
  • 2
    +1 for recommending Clean Code. – Dave Kirby Feb 13 '10 at 13:23
  • 1
    @MarkJ I prefer writing code which does not need comments, instead of spending extra effort on keeping them up to date. – Péter Török Feb 13 '10 at 13:35
  • 1
    "When the code and the comments disagree, they're probably both wrong" – Wayne Conrad Feb 13 '10 at 14:33
  • @PéterTörök I was wondering: could writing clean code influence performances? I mean, in your example you replaced an _almost directly evaluated condition_ with a function that probably will test that condition and then return true or false depending on the result. This means, instead of testing the condition directly, you have to make a function call, and that function maybe contain an if itself with the same condition, which in turn could be _not clean_ or could need comments. To be clear: I'm not arguing against your points, just asking. – Overflowh Aug 22 '14 at 18:50
  • @Overflowh a good compiler should be able to inline small functions like that. – Andy Apr 01 '17 at 16:17
  • @PéterTörök using expressive functions is one of the best ways to increase clarity in my opinion. We have to keep in mind that we're not just *using* a programming language, we're actually *creating* our own language constructs on top of it, and we want those constructs to be as clear as possible. – Andy Apr 01 '17 at 16:18
  • @PéterTörök I rely on comments to explain mathematically or conceptually tricky things that can't be expressed merely by clear function names, variable names, or program structure. – Andy Apr 01 '17 at 16:20
25

I don't think you can normally write code without comments.

Briefly, the code documents how. The comments document why.

I would expect the comments to indicate the conditions why the code has been written like that, limitations imposed by requirements or externalities, the impact that would result from changing the code, and other gotchas. The comments contain information that isn't contained within the code itself.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • 1
    @Brian: and what guarantees that those comments are updated accordingly when the code changes? And what is the use of a comment which tells me why the original version of the code _n_ years back - which often bears not the slightest resemblance to the current version - was written the way it was? – Péter Török Feb 13 '10 at 12:48
  • 2
    @Peter You guarantee comments are updated by using code reviews or pair programming. – MarkJ Feb 13 '10 at 13:00
  • I would recommend paying more attention to writing self-documenting code than writing comments. I often see too many comments in code that don't really need it. – willcodejavaforfood Feb 13 '10 at 13:12
  • @MarkJ OK, good point. Unfortunately in real life very few projects use these methods :-( – Péter Török Feb 13 '10 at 13:19
  • 2
    @Peter - nothing can provide the guarantees you're after, I'm afraid. You have to maintain the code and the comments together. I would expect the code to change more often than the comments, given the above criteria re. comments. – Brian Agnew Feb 13 '10 at 13:55
  • @Brian That's my point and that's exactly why I prefer self-commenting code: less worries for me. But this is just my 2 cents. – Péter Török Feb 13 '10 at 14:07
  • 3
    @Peter: self documenting "why" is quite hard, to do it fully you will end up with variable names like "HashMap aConcurrentHashMapIntentionallyNotUsedHereBecauseOfTheUsagePattern" – Fredrik Feb 13 '10 at 14:37
  • @Fredrik I updated my answer to explain my point better. – Péter Török Feb 13 '10 at 19:46
7

Comments along the code are supposed to tell you why you initially did something a certain way. It shouldn't mean the code is too hard to understand.

Gal
  • 23,122
  • 32
  • 97
  • 118
4

The most important things to follow are:

  • give your variables, methods, classes... meaningful names
  • write classes/ modules with a clean responsibility
  • don't mix up different levels of code (don't do bit shifting and high level logic inside of one method)
tangens
  • 39,095
  • 19
  • 120
  • 139
2

I think it is useful to write comments for USERS of your code - what the classes/methods/functions do, when an how to call it etc. In other words document the API.

If you need to comment how a method works for the benefit of maintainers then I think the code is probably too complex. In that case refactor it into simpler functions, as others have said.

Dave Kirby
  • 25,806
  • 5
  • 67
  • 84
2

I personally feel that having no comments at all is about as bad as having excessive commenting. You just need to find the right balance. About using long descriptive names for things this about sums it up for me: read this Also read Kernighan & Pike on long names.

rvirding
  • 20,848
  • 2
  • 37
  • 56
1

You need to follow certain rules.

  • Give the entities (variable, classes, etc) readable and meaningful names.
  • Use design patterns extensively and name them accordingly, e.g. if it is a Factory name it FooFactory.
  • Have the code formatted properly, etc.
fastcodejava
  • 39,895
  • 28
  • 133
  • 186
  • 1
    If you are going to use a design pattern then yes, for gods' sake, name it accordingly. But I'm not convinced that use of design patterns itself is a plus for readable code -- especially in Ruby. – Shadowfirebird Feb 13 '10 at 23:11