Hacker News new | ask | show | jobs
by jasonlotito 4960 days ago
Intention is all well and good, but imprecise. It also is not accurate to suggest that what is written is what is intended. One of the best ways I know of to describe intent is with tests. Not only do well written tests describe exactly what is being done, but it also tests to enforce this. There is no mistake about what it expected and intended.

A comment, on the other hand, cannot be trusted. Ignoring the fact that it could simply be out of date and wrong, your interpretation of intent might not the same as the person writing it. A lot of this might be because you simply don't share the same context. After all, when this comment was written has a context beyond the location of the code.

2 comments

There's no need to trust a comment, it simply tells you what the author was thinking, as best as s/he could express it. It's less imprecise than no comment at all. Suppose you have a very simple function that does something clear - reading the code you can tell what it does and how. And suppose that function is called from several hundred different contexts in the codebase, but one of those contexts causes an exception in your simple function.

You could "fix" it, with a code change. But what if your fix goes against the assumptions of some other context where the same function is called? A comment that describes what the function "should" do allows you to decide whether changing the function, or its caller, will be more in line with the design of the overall codebase. This is particularly true with mature codebases where thousands of tiny fixes and tweaks have accumulated over time. There's a corpus of learning about why the code ended up that way that even in-depth reading of individual functions might miss.

Tests are good, and to be encouraged. But using tests in place of comments is rather like answering a question with a question. Tests provide confidence, they do not provide understanding.

Of course, you could do an in-depth analysis of every function, in every context it's used, and how it interacts with its callers and callees. While you're doing that, the guys who commented their code will be moving onto the next challenge.

"A comment, on the other hand, cannot be trusted."

Badly written comment cannot be trusted. Good comment will be changed much less frequently than code or tests and it will stay relevant and precise.

It's not impossible to write such comments... Just insanely difficult.