95 points · by holman · 15y ago · 79 comments
In recent software development efforts I have run, I have put for the rule that "All comments are bugs". Comments get separated from the code, make statements about obsolete activities, and often mislead the reader, and even sometimes the author.
In place of comments, write code that is as self-explanatory as possible.
I refer to Martin Fowler's "Refactoring" as a way of trying to increase my authority in the matter.
However, I do back off from this extreme position and put comments on individual methods. Sometimes. What helps is using longer method/function/attribute/variable names than pg or tptacek would.
I think the TomDoc example is particularly poorly chosen for the author's thesis, as, more often than not, one is likely to just do "text * num_duplications" inline, no? So why is this even a separate method? Certainly not to save lines of code.
As noted in other comments to this submission, the real value of comments is the why of doing something unusual, not what.
And who was it that said that the Ruby community should spend more time on documentation rather than tools for documentation? A case in point is the doc for EventMachine. This is an insanely useful tool, yet every time I look for the answer to a question about how it operates, the auto-generated documentation leaves me disappointed.
If you are going to spend time on documentation, there is the place to spend it. Make your code readable in its own right.
What helps is using longer method/function/attribute/variable names
Sounds great, so why don't all good programmers do that? This is a deeper question than it seems. Over time, I've come to mostly prefer short names. The reason is that longer names add lexical noise to the code; they distort its structure and thus drown out other important information. The lexical is only one of several semantic channels and there are tradeoffs between them: you can't optimize clarity via verbosity. After a certain point (rather quickly, in fact) inflating the code detracts from clarity overall. It's easy to miss this because one often is making X more readable by giving it longer names or spelling its logic out in detail. The trouble is that other things than X have now become more obscure. The question is, what maximizes the clarity of the program as a whole?
I'm pretty sure my code would evoke howls from the "all code must be immediately readable [to me]" brigade. I used to feel the same way, but now I don't. It leads to sacrificing deeper comprehensibility (of the entire program) for superficial readability (line-by-line). Maximizing the overall clarity of a system is closely tied to distilling its parts, and the connections between them, to their minima. Code inflation inhibits this.
The demand for immediate readability comes from a belief that all code should reveal its secrets immediately. That would be great, except it's impossible. There's a fundamental complexity tradeoff at work. If you opt for verbose readability, you end up with code that is line-clear (I know this function is saving a record to a database or whatever) but system-incoherent (why the hell is it going to the database here?)
Talented programmers who care about readability but have a superficial view of what that is end up producing systems with far too much code. They accrete code, which may be impeccably pseudo-readable, when what they ought to be doing is distilling it. Such code is like the old joke about the person lost in a hot air balloon who calls down and says "where am I?", but the guy they're talking to is a technical person who answers, "you're in a balloon twenty feet above the ground".
Programs that are built for global intelligibility usually have much less code, but not necessarily the sort you can scroll to and immediately grok. You have to work to begin to understand the program, but once you absorb its conventions understanding proceeds much more rapidly. Latency is worse this way, but bandwidth is orders of magnitude better. The reader I feel responsible to is the one who is willing to put in this work. After all, they're going to have to do it anyway to get anywhere nontrivial.
What do you think of short methods?
I'm skeptical of them. I think it's a mistake to try to make functions short for the sake of making them short. It's a mistake because adding a new function also adds complexity (i.e. more code, plus opacity between the calling and called) - not a lot, but greater than zero - so introducing a function is not cost-free and its benefit needs to be greater than its cost. I found that once I started asking functions to justify themselves this way, I began creating fewer functions and the overall complexity of my code went down.
Factoring code into functions is one of the best tools we have, of course, but people commonly make the mistake of applying it mechanically. A function should exist when the program itself wants that concept, not because you had a block of code that was too big or some duplication and you wanted to rearrange the pieces. The way to address those symptoms is not by adding more code but by thinking until you see how you were looking at the problem wrongly. Then the new concepts, and finally the new functions, appear by themselves.
You only have so many conceptual cards to play and must play them sparingly if you don't want your program to succumb to runaway complexity. A good function is a logical construct that makes sense in the meaning of the program the way a good word makes sense and adds a unique meaning to a language, something you can't quite say as well any other way.
When all you're doing is shifting pieces around, you're missing the most important thing about functions, which is this conceptual payload. After you do that for a while, your program stops evolving as an expression of the problem being solved, because you've built it out of primitives that refer only to the internals of the program rather than to concepts drawn from the problem space.
Side note. I'm writing at such length here and in the GP because these questions are on my mind all the time. I've been working on a hard problem for over two years now in an utterly immersed way, the kind where you dream about it every night, where time itself begins to blur. Our approach has been to evolve the program many times until it converges on a solution. The only way to do this is if the program doesn't grow as you evolve it. How do you build a system such that you're constantly adding new information and behavior to it, and yet the overall code doesn't grow? We've had to figure this out just to stay alive.
One more thing about function length - Steve McConnell cites studies that suggest that short functions aren't easier to understand. IIRC the sweet spot was between 50 and 100 lines, depending of course on the language. I've posted references to this on HN before. One should be careful about believing these studies because the empirical literature on software development is so poor. But it's at least interesting that such experimental evidence as exists runs counter to the "OO short methods" school.
In reading over the comments I've written, a majority of them document the various methods of working around bugs on third party components we can't fix. Ah, the joys of working with proprietary, non-source libraries.
I don't think I'd need an 11 line comment to tell me what this definition did:
def duplicate_text( text, num_duplications )
text * num_duplications
end
In fact, I might prefer NO comment, because comments can become out of date and misleading, whereas the code always tells the truth."If you don’t have an absolute clarity in the code you’re pushing, it rears its head by way of bugs, confused coworkers, and slow code."
That's the single most confusing function name I've seen in a while.
def duplicate_text(text, count):
"""humbledrone, you effing moron, just inline
the effing astericks"""
assert FalseDocumentation is important, its just how its done today that bothers me. I have been reading the book "Computational Semantics with Functional Programming" and it has been quite intriguing. I would highly recommend it.
> Perform an n-fold frobulation. > @param n the number of times to frobulate > @param x the x-coordinate of the center of frobulation > @param y the y-coordinate of the center of frobulation > @param z the z-coordinate of the center of frobulation
could be "Frobulate n times around the center (x,y,z)." (From http://stackoverflow.com/questions/499890/what-is-your-perso... )
So the example would go "Return text concatenated count times." I'd try rewriting the longer example from a diff message in the OP, except it didn't fit in its own snippet!
A wordy style makes writing and maintaining comments feel like a chore; feeling like a chore, it gets done less. People start finding reasons comments are bad, and taking them for the whole story.
So sure, we all know its great to document. The challenge is figuring out how to get it done. Given that we're all in a hurry, mean well but think we'll get back to it.
It feels like you're doing something when you paste in all those blank comment blocks. But soon you don't even see them, since first off they're usually blank, and second when debugging you're looking for the code not the comments, since if it all worked like its commented then there'd be no bugs.
Unless it is no longer supposed to work how it was originally written and commented. Software lives and evolves over time. All too often comments go stale. When the Big Bug Day comes, many hours will be wasted on such legacy comments.
Also, whenever we made a change, we put a comment (at the top of the class, function, method or whatever is changed), also timestamped, with a reference to the change request ticket (or equivalent), and a summary of the change.
Old comments were deleted if necessary (you could always look them up with a diff on the source control)
Said ticket also had a reference to the code file :) so you had 100% traceability.
The downside being of course it was all very bureaucratic, but there were legal requirements to fill and it was a sensitive, finance sector company. That setup probably wouldn't work for a fast-paced startup :)
Edit: or maybe not, I can't see mention of it on tomdoc.org. However the format lends itself to that.
For contrast, the D language allows inline tests.
The other case is API docs for libraries and frameworks meant for external consumption.
Commenting what code does -- is either 1) pointless or 2) indicative you should rewrite your explanation-requiring code in a more straightforward fashion.
Programmers take code seriously. Most don't take comments seriously, even when they believe they ought to. You might say they're bad programmers, but I don't think it's that simple. I think the attention goes straight to code for a reason.
Braces (in relevant langauges, like C and Java) are even better, because they tighten scoping and avoid unintentional variable re-use.
[1] http://www.amazon.com/Clean-Code-Handbook-Software-Craftsman...
In your example something like textByRepeatingText(text, times)
It might fits your thinking, but it certainly doesn't mine. Documentation is the common language (hopefully).
Let's assume the supposed best-case: every single method and class is commented using a language-specific documentation system (I'm thinking of EDoc for Erlang, Javadoc for Java, etc). Who cares? Congratulations: I now know how all your functions work. But what is the system architecture? How do object instances of the different classes hang together to support the functional specifications? What is the sequence of events for various successful and failed transactions?
I suppose what I'm complaining about is the rationale that code commenting can necessarily substitute a solid set of functional specification and design documents. Then again, noone here made this suggestion, so maybe I'm just whining into a black hole. The only open-source project that comes to mind when I think of an astoundingly high quality of documentation is SQLite in the form of "Inside SQLite (2007)" (O'Reilly); unfortunately it's not free.
The project can grow both in terms of code size and the number of people engaged. Each drives up the importance of documentation.
Especially if one uses the incremental iteration paradigm, the commit history together with the code diff IS the documentation of one's code in it's most fundamental way, that is when I changed something, why, what I was ( thinking that I was ) doing etc.
In case that one has to maintain existing code, of course, the whole history is not available but still, refactoring committed similarly documents the evolution of the code in a similar way.
Both are important of course. ;)
unless multiplex('Tom', 4) == 'TomTomTomTom'
raise TestError( 'multiplex() failed' )
end
Not only does that test communicate the exact same thing as the documentation comment, it is guaranteed to be correct and not out-of-date (assuming it's run as part of a test suite), whereas the comment can easily be wrong. multiplex('Tom', 4) == 'TomTomTomTom'
I'd argue that's a failure of the api designer that no amount of documentation is going to make up for.Examples are good, testing is good, executable, testable documentation is doubly good, and predictable, intuitive api interfaces are invaluable; everything else is a liability that is going to go stale.
I've deleted my post and have decided to argue my point in another fashion. Please enlighten me to the meaning foo(), here is the documentation:
tests = [
#Format: [InputA, InputB, InputC, InputD, Output1, Output2]
[1, 2, 3, 4, 12, -7 ],
[2, 3, 4, 5, 27, -14],
[3, 4, 5, 6, 48, -23],
[4, 5, 6, 7, 75, -34],
[5, 6, 7, 8, 108, -47],
[6, 7, 8, 9, 147, -62],
]
for a, b, c, d, o1, o2 in tests:
failUnlessEqual((o1, o2), foo(a, b, c, d))
Can you tell me what foo() does please? Its a ridiculously simple function. I work with tests like this quite often. It doesn't confuse me though, I like to put comments in my code and even the test code, but you don't need those.Yes, a poorly written test for a horribly named function with impenetrable argument names make for a shitty experience for the api user, but is that really insightful? Hopelessly meaningless method names with impenetrable arguments would be just as shitty to use if they came with a page-and-a-half of prose.
And if the hypothetical idiot who wrote your hypothetical test-as-documentation is the same idiot who would instead by providing some other form of written documentation, why would you expect it to be any more clear?
I've heard the idea before and dismissed it, but it's surprising now how often I will go back and check that journal for why I did something.
I already try to write informative git log entries, but the journal really lends itself to long form exposition.