Just two years ago, I was beyond skeptical towards the forces telling me that comments are
worse-than-useless, self-injuring blocks
of unexecutable text in
a program. I thought the idea was downright ludicrous. But as I've made an effort towards reaching this nirvana called "self-documenting code," I've noticed it's far more than
a pipe dream.
The first thing you have to do is throw out this notion
of gratuitously commenting for the sake
of commenting that they teach you in school. There's no reason every line needs to be commented with some text that simply reiterates what the line does.
After that, we can examine some seemingly rational excuses people often use to comment their code:
-
The code is not readable without comments. Or, when someone (possibly myself) revisits the code, the comments will make it clear as to what the code does. The code makes it clear what the code does. In almost all cases, you can choose better variable names and keep all code in a method at the same level of abstraction to make is easy to read without comments.
-
We want to keep track of who changed what and when it was changed. Version control does this quite well (along with a ton of other benefits), and it only takes a few minutes to set up. Besides, does this ever work? (And how would you know?)
-
I wanted to keep a commented-out section of code there in case I need it again. Again, version control systems will keep the code in a prior revision for you - just go back and find it if you ever need it again. Unless you're commenting out the code temporarily to verify some behavior (or debug), I don't buy into this either. If it stays commented out, just remove it.
-
The code too complex to understand without comments. I used to think this case was a lot more common than it really is. But truthfully, it is extremely rare. Your code is probably just bad, and hard to understand. Re-write it so that's no longer the case.
-
Markers to easily find sections of code. I'll admit that sometimes I still do this. But I'm not proud of it. What's keeping us from making our files, classes, and functions more cohesive (and thus, likely to be smaller)? IDEs normally provide easy navigation to classes and methods, so there's really no need to scan for comments to identify an area you want to work in. Just keep the logical sections of your code small and cohesive, and you won't need these clutterful comments.
-
Natural language is easier to read than code. But it's not as precise. Besides, you're a programmer, you ought not have trouble reading programs. If you do, it's likely you haven't made it simple enough, and what you really think is that the code is too complex to understand without comments.
There are only four situations I can think
of at the moment where I need to comment code:
- In the styles of Javadoc, RubyDoc, et cetera for documenting APIs others will use.
- In the off chance it really is that complex: For example, on a bioinformatics DNA search function that took 5 weeks to formulate and write out. That's how rare it is to have something complex enough to warrant comments.
- TODOs, which should be the exception, not the rule
- Explaining why the most obvious code wasn't written. (Design decisions)
In what other ways can you reduce
clutter comments in your code? Or, if you prefer, feel free to tell me how I'm wrong. I often am, and I have
a feeling this is one
of those situations.
What are some other reasons you comment your code?
Update: I forgot to mention that discussions on relatively recent blog posts by
Brian Kotek (Don't Comment Your Code) and
Ben Nadel (Not Commenting and The Tipping Point of Poor Programming) got the creative juices flowing in
my brain for this post. Thanks for bringing it up, gentlemen.
Hey! Why don't you make your life easier and subscribe to the full post
or short blurb RSS feed? I'm so confident you'll love my smelly pasta plate
wisdom that I'm offering a no-strings-attached, lifetime money back guarantee!
Leave a comment
Back in the mid 1990's when I worked in the Avionics Defence industry, we used to have to design our code in Pseudo-code comment form. This would then be reviewed(sometimes many times) in meetings before turning it into real ADA/CORAL 66 code. The comments were always left in. But this was a long time ago :-)
Posted by Neil Cooper
on Feb 26, 2013 at 08:09 AM UTC - 6 hrs
There was a chapter about this in the book Code Complete, and I was a fan at one point, even doing it myself:
http://www.codeodor.com/index.cfm/2007/2/10/The-Ps...Nowadays I really only do it if the problem I'm working on is particularly hard for me to grasp, and I'm ashamed to say I don't remember the last time that was. I guess I should work on harder problems!
Posted by
Sammy Larbi
on Feb 26, 2013 at 08:30 AM UTC - 6 hrs
I only did it because it was company/Government/Military standard. Naval Sonar, F-16 and F-22 Helmet and Head Up Displays and Eurofighter Flight control work required it.
I'm in the UK but a lot of the work was for the U.S.A - I was a grunt, a drone software engineer just doing what they were told. It was actually intensely dull :-)
I'm glad I now work for a TV company.
Posted by Neil Cooper
on Feb 26, 2013 at 08:40 AM UTC - 6 hrs
Cool - what kind of work gets done at a TV company? Websites, I'd imagine, but what else?
Posted by
Sammy Larbi
on Feb 26, 2013 at 08:58 AM UTC - 6 hrs
I work for BSkyB (
http://www.sky.com/) 100's of TV channels + over 50 HD and 3D channels.
My work constists mostly of Web and Interactive TV at the moment but also we have the Sky+ app that allows you to look at the TV listings and put your set top box onto record from anywhere in the world as long as you have an internet connection. There is also the Sky GO app that allows you to watch live TV channels, on demand movies etc. Sky Sports allows you to watch multi screen Sports including the 9 feed Formula one racing. There are sky news apps .. actually the list is endless.
http://www.sky.com/products/ways-to-watch/sky-apps/index.html" target="_blank">
http://www.sky.com/products/ways-to-watch/sky-apps...
NOW TV (
http://www.nowtv.com/) internet TV service.
There is also games dev for Sky Games or different channels such as MTV. I'm doing some work with Disney and FX channel at the moment.
Special effects work, graphics work for TV Shows and films, Internal applications for different departments..
Needless to say, the S/W Engineer Dept. is pretty big.
Posted by Neil Cooper
on Feb 26, 2013 at 10:11 AM UTC - 6 hrs
oops. I'm not sure how some HTML got into that post ?!?!?
Posted by Neil Cooper
on Feb 26, 2013 at 10:12 AM UTC - 6 hrs
Wow, that sounds amazing! What's the interactive TV stuff like? Like for DVR, channel guides, and whatnot, or something else?
Re: the HTML in the url ... looks like my regex could use some work in IDing URLs as well. =)
Posted by
Sammy Larbi
on Feb 26, 2013 at 10:34 AM UTC - 6 hrs
The interactive TV stuff ranges from sports/news multiscreen video/info/stats tv applications (like F1 racing which looks like this
http://e1.365dm.com/13/02/496x259/redbutton_289579...) to games and booking facilities. In the past you could do banking and shopping too but there isn't so much of that any more.
Voting apps for TV shows (X-Factor, Talent shows, other rubbish) is also big in the interactive TV world.
Some channels have a permanent link to interactive apps via the red-button on the remote control.
Posted by Neil Cooper
on Feb 26, 2013 at 11:26 AM UTC - 6 hrs
Wow, that stuff looks really cool. I cancelled my cable TV, in part because of how terrible the interface was to do anything. I think they've come a long way since then, but I'd be surprised if it was as nice as the stuff you're showing there.
Thanks for enlightening me! =)
Posted by
Sammy Larbi
on Feb 26, 2013 at 12:23 PM UTC - 6 hrs
Only "bioinformatics DNA search function that took 5 weeks" deserve comments? OK, ok, ok. I get the point... just anything that not understand by NOW ...
Posted by 0zkr
on Mar 04, 2013 at 10:09 PM UTC - 6 hrs
Yeah, I'd expand it a bit and make it anything fairly complex. But a lot of code is not very complex, and you end up seeing comments like // loop over the collection, for a contrived example.
Posted by
Sammy Larbi
on Mar 05, 2013 at 06:33 AM UTC - 6 hrs
I think it's nice to see a comment above some regular expressions. If I stare at one on a Monday morning I would really like a bit of a pointer to what it's doing so I don't have to work it all out.
But then again I'm not very good at them ;-)
Posted by Neil Cooper
on Mar 05, 2013 at 06:36 AM UTC - 6 hrs
I could see that.
Posted by
Sammy Larbi
on Mar 05, 2013 at 07:41 AM UTC - 6 hrs
I usually put a one-line comment above sections out of pure habit. I probably don't need to do it because no-one else is actually going to be editing my source. However...
"Code can only tell you how the program works; comments can tell you why it works. Try not to shortchange your fellow developers in either area."
http://www.codinghorror.com/blog/2006/12/code-tell...
Posted by Ali
on Mar 20, 2013 at 02:22 PM UTC - 6 hrs
Hi Sam.
I found the article quite interesting and enlightening.
Thanks.
But I have another excuse to write comments. Wonder if you could address it.
Well a lot of time we code something based on some logic and some circumstances(or use-cases i.e. the same set of code address various problems), however later I find that some person(not particularly bright) has considered only one use-case and in order to modify some new enhancements in that particular use case gone ahead and modified the code such that the other use-cases have gone amiss.
e.g. I have a method -
object appendtypeforstring(object ob){
if (ob is string)
ob += "is string";
return ob;
}
When some juniors are optimizing this function, they might see some execution of this method with string args and assume this is called only with string arguments and hence might remove the if (obj is string) to optimize. Hence here i would recommend adding the comment {// append string if ob is string, otherwise return the object as is ... or something like that}.
The point(or excuse) i am trying to make is that there are times when I feel that some one of not so high intellect might mess up my code and I feel that a comment is required.
I would appreciate it if you could express your views on this and throw some light on the problem.
Thanks.
Posted by Dev ray
on May 27, 2013 at 11:27 PM UTC - 6 hrs
and adding the that many times I come across code that I feel .... why is it there ?? its not required?? but I go crazy trying to find out if we can remove it or not ...
e.g-Suppose later someone divides the above function into 2 overloaded functions
object appendtypeforstring(string ob){
if (ob is string) // {1}
ob += "is string";
return ob;
}
and
object appendtypeforstring(object ob){
if (ob is string)
ob += "is string";
return ob;
}
the obviously line marked by {1} becomes redundant and should be removed, but he does not remove it. In this case it is simple but in some complicated cases, some code we feel is redundant might be serving some "higher purpose" and I go crazy trying to figure it out(honestly we usually prefer leaving it as it is than risking a system crash somewhere else).
but a comment stating its purpose would let us clean up the code better.
Hence I think that comments should be used a bit graciously. Not go overboard, but use it graciously for someone in the future who is not as smart as us :).
Please feel free to correct me if I am wrong.
Thanks.
P.S. - I apologize if you feel that my concern is stupid and that I have wasted your time.
Posted by Dev Ray
on May 27, 2013 at 11:45 PM UTC - 6 hrs
Dev Ray - No, it's not a stupid concern nor a waste of time. However, I'm not convinced this is a good use of comments.
For instance, if you have made this as a small change instead of as a small part of a larger feature, you might find the reason why in the commit message (assuming you're using version control). If I have a question about why something was done, I'll often first look there to see if they left a comment as to why, or to see what else was changed to understand it.
Also, in this case, I think it could be more clear from the function name that you want it to behave this way. It's pretty clear already, but what if you named it "appendTypeIfString" instead of "appendTypeForString" ?
Or, you might make it more clear by using an else, so it looks obvious that there is a case for strings and for objects that aren't strings.
For your second case regarding the overloading, I typically will just remove any code that is obviously not executed (or if executed, will always result in the same result), but I could see how a junior might not do that.
In this case, I think having automated tests to cover the behavior is very useful. Then you don't need to fear it so much.
In the end, I think if fear of changing code is the motivation for using comments, there are better ways to alleviate that fear. In the case you presented, it's very easy to reason about the code so maybe with a comment you can easily tell if it's telling the truth or not (but if you can, that's one less reason for the comment). On the other hand, if you feel the need to comment some code because it's hard to understand, then I don't find the comment that helpful (because I can't easily tell if what it says matches what the code really does) and would much rather have easier to understand code.
If the code is doing something or doing it in some manner that people might question "wtf was going on here" you probably ought to leave a comment as to why. For example, suppose your project is using an ORM, but the query it generates is very slow. So you write the SQL by hand, and I'd leave a comment saying "we broke from using the ORM here because the query was much too slow. we got X improvement by switching to hand-written SQL" or something like that.
Hope that helps.
PS: Feel free to ask a follow up!
Posted by
Sammy Larbi
on May 28, 2013 at 02:09 PM UTC - 6 hrs
Thanks for the new insight.
Yes the version control would be a good place to leave explanations. You would check it, but would Everyone :)? but I guess we could have it in the code of conduct/ good practices and include it in induction/training so that everyone would.
Yes, of course the code snippets used were only for demonstration purposes and in reality we have a bit tougher logic :) but I agree that the code could be more "self documented". Would keep it in mind in future.
Automated Test Cases!!! I wish... but we don't have that luxury(dearth of time)... but maybe some day ...
Well... I appreciate you taking time to reply.
I still feel that since different people view things differently and have different logic/strengths, hence clarifying things would be better but ...
Let me ponder on the above, put it into practice and see if my perception changes.
Again, appreciate your time.
Thanks :)
Posted by Dev Ray
on May 29, 2013 at 06:51 AM UTC - 6 hrs
I sometimes put a comment to explain what objects and/or functions i needed in an import/include of certain files if it would usually seem strange to do so, like including iostream solely for debug info with some console I/O i.e
#include <iostream> /* using std::cout */
so people (Myself) can decide whether or not to remove a library easier.
Posted by James
on Jan 10, 2014 at 04:49 PM UTC - 6 hrs
@James That seemed like a good idea to me at first, but what if someone adds to the code using something extra from iostream but doesn't update the comment?
Plus, in a compiled language, I'd feel comfortable removing that since it wouldn't compile without it, and all places that used it would become immediately obvious.
Now in an interpreted language, you won't get that, so maybe there's more of a benefit there. (Although if you have solid test coverage, I'd not fear removing it.)
Posted by
Sammy Larbi
on Jan 11, 2014 at 11:08 AM UTC - 6 hrs
Version control, documentation, more subroutines and the like are excuses for not to comment the code properly.
Posted by Leo Lucas
on Jul 25, 2014 at 08:35 AM UTC - 6 hrs
There was no such a thing as a good variable name in Fortran 77, which I used until some years ago.
Posted by Leo Lucas
on Jul 25, 2014 at 08:37 AM UTC - 6 hrs
Sure, but I don't think we can say "because one language makes it impossible we cannot rely on it in other languages" =)
Posted by
Sammy Larbi
on Jul 25, 2014 at 08:53 AM UTC - 6 hrs
In scientific simulation, sometimes you are a collaborator or you have a boss, and you work with someone else's code, so that you can't restructure the whole code as you want. They don't let you do so because they are affraid of no longer understanding the code after you change it. Or that you simply add a lot of bugs to a working code. And doing so in parallel would require too many extra-hours that you really don't want to spend in programming. So what's left? Commenting the most complicated parts of the code while hoping that this will help you understand it. Or sending the link of this page to your boss...
Posted by Leo Lucas
on Jul 25, 2014 at 09:11 AM UTC - 6 hrs
Well, it's only a goal. If it proves impractical because of political pressure, it's fine to fall short of the goal. Of course, if you just prefer to do things differently than what I suggested in the article, that is fine too!
Posted by
Sammy Larbi
on Jul 25, 2014 at 10:31 AM UTC - 6 hrs
There's one important reason that people don't mention very often... "comprehension time".
I work on a fairly large team of developers on a large code base written in C and ASM. In all but the most obvious cases, it is generally faster to read a comment at the top of a subroutine than it is to read a bunch of code to figure out what is being done.
For example, I might be reading through some code - maybe trying to figure out what might have caused a bug, and I'll come across something like this:
if (some_sub()) {
...
If the subroutine name is not glaringly obvious, I have to go read the code, and if there is no comment at the top of the subroutine, trace through the implementation of some_sub, looking at all the possible return paths and return values to see what they are, and what they mean. This can take 10 seconds, or 10 minutes and sometimes much more - particularly if that routine calls other equally ambiguous subroutines. And I may not even care about any of this - I just want to know what it means when some_sub returns true or false, so I can trace through the high-level logic of the main code.
So for me the primary measure of code readability is this: "How fast can a programmer of some given skill level grok the code". And anything we can do, as programmers, to accelerate the comprehension of our code, is worth the effort.
So my primary reason for adding comments is to speed up comprehension of the code.
Posted by Jak
on Aug 12, 2014 at 08:54 PM UTC - 6 hrs
I'm not sure how well this applies to ASM, to be honest. But I would say "if the subroutine name is not glaringly obvious" then make it so.
In general, if we can't take the time to make the code obvious, I'm skeptical of us making the comments much better, including having the discipline to keep them up to date.
The code does what it does. The comment may help you understand it, but it can be out of sync with the code.
Posted by
Sammy Larbi
on Aug 16, 2014 at 10:08 AM UTC - 6 hrs
That's a succinct way of putting it, Tim. +1 from me!
Posted by
Sammy Larbi
on Feb 20, 2015 at 06:24 AM UTC - 6 hrs
All code should read well, and have meaningful class, function and variable names to the purpose and reason for existing. However no comments, make meaningless flow, a lazy/unpolished finish and is a snobs belief.
Posted by John Smith
on Jun 05, 2019 at 12:18 PM UTC - 6 hrs
Leave a comment