While running on the beach, I stumbled upon the bottle below. Inside was a memorando to the writer's future self, detailing present events and pitfalls.
In a way, that’s what commenting should be about; a message to thy future self conveying the why’s of here and now. You’re most likely not the one who’s going to read it, but that rusty piece of code washed away by years of sunshine and salt you left for the world, it'll definitely be better with an attached message.
The note I found was emotionally sound. Everything you’d expect from a silo to the future. Writing proper comments though, even accounting for the poetic aspect of code, should stick to some rules.
1) Code is better than comments.
While the following Java method comment may look ok, it probably has better alternatives.
// returns null if no such user is present (PROBABLY BAD COMMENT!)
public void String getUserNameById(long id);
If you’re using an editor like IntelliJ, you should use @Nullable
or @NotNull
to make your intentions specific. If not, you always have the handy Option<String>
which will add run-time checking.
2 Document intention, not functionality
From the programmers' bible, Code Complete, you get that IBM did a several months long study where maintenance programmers reported that the most difficult problem they faced was grasping the author's original intent.
// allows the usage of 6 digit TLD's (BAD COMMENT)
\b[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}\b
The above regex parses emails. The comment merely describes a problem the programmer had with Top Level Domains. It’s not descriptive of its intent and merely focuses on the functionality. The comment below not only specifies intent, but also provides the foundation for the chosen rules.
// parses emails according to RFC3696 - https://tools.ietf.org/html/rfc3696#page-5
\b[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}\b
While hard to do while your mind is circling the problem at hand, comments should focus on the why's and not the how's. Only arcane how's should be documented, and mainly to provide insight into the why's. Here be dragons.
About that bottle? I did what anyone would do, tagged it with #mafaldasmessageinabottle and freed it back to the ocean.
As an Amazon Associate I may earn from qualifying purchases on some links.
If you found this page helpful, please share.