More Like This
Categories (See All)
The Importance of Commenting Your Code UNDER REVIEW
By kbenderoth89 | Published May 29 2012 07:55 AM in General Programming
comments code word explain comment function you' programming doing
I've been a student at Full Sail University for a while now, and one thing I CONSTANTLY see from students, online forums, and programming related forums, is the lack of comments. I cannot count how many times I hear about people going to the creator of said code saying "why is this working?", "how are you doing this?" Sure, it's always nice to google "how to capture motion in a game" or "how to use FMOD" and have all access to open code sources to allow us to do something that may have taken us hours of API documentation reading or a lot of 'head banging against the wall' time. However, are you always going to be able to do that? Is everything you want to do easily written somewhere on the internet? Probably not. A good programmer doesn't need to lookup how to dynamically allocate an array every time he needs one. He should be able to look it up once and fully understand what is going on in the code and how to do it. a good programmer comments as much as necessary. You want people to understand what you're doing, and why you're doing it. So here are some tips on commenting.
1. Know your audience
Think about who will view your code. Are you on a team? If so, think of the information they need to know to do their part.
This is for any of the programmers working with the camera. Perhaps making the cinematics.
2. What purpose does your code provide?
Are you doing this code for your personal use? Maybe your making a program involving Direct2D to reference in any future programs involving Direct2D. In that case, you should use comments to explain why you're using a function or factory. Explain the process so thoroughly that you can look at the program years from now, and be able to recite the steps in your sleep. Is the code to teach beginners? Do the same thing. explain it as if the person reading has no idea what DirectX is. Think of a person who knows nothing of your coding language....keep that guy in your head, and comment, comment, comment.
3. No such thing as too much commenting
Too much commenting is non-existent! Remember: someone reading that code may not know ANYTHING about programming. Or maybe they just don't know anything about whatever you're doing. If someone specializes in Object-Oriented C++ and he's switching over to C#, he can skip a LOT of basics (but not all) so he may go straight to the advanced stuff. You're thinking "if someone's looking this far into C# then he definitely knows his C#" well think again. Gurus of one language may be ignorant and skip ahead in another language to save time. There is, however, such thing as too little.
This would be an introduction for C++ to those who just got through the basics in an intermediate lesson:
Now I don't know about you guys, but if I was a noob in programming, I'd think "wtf are two star thingies doing there!?" A better introduction for replacing the simple main to the more useful main:
*Whether you use single line comments or block comments is entirely up to you.*
Was this too much? NO! Was this too little? Perhaps. It largely depends on your audience. You could, for example, further explain the varieties of the return value? You could also explain what exactly arguments are? Maybe explain what this version of main does that the previous version doesn't?
4. Format any way you want
Here are some examples of formatting your comments, using a function I made in a word jumble game
There are many different ways you can use your comments. You can make them look pretty or fancy, you can put them in a boring paragraph, you can put them in step format, you can put them anywhere you want any way you want. Best rule of thumb is to put them up somewhere the user will definitely not skip over by accident.
5. Comment ALL your work
Don't be stubborn! Saying "this stuff is so easy, how could I ever forget this?" is just ignorant. My uncle graduated as a programming major. Twenty-two years later as a computer engineer, he saw a new job opening in his company involving C programming that paid a lot more. Unfortunately, spending the years playing with hardware instead of programming software doesn't keep that stuff in your head. He didn't even remember what a virtual function was. Typically if you learned something, no matter how long it has been, you can refresh your memory much quicker than you can imagine! But to his horror....he didn't comment when he was learning about virtual functions. OOPS! Comment ALL your work! I cannot stress this enough. Don't be stubborn and ignore commenting that lesson about the difference between an integer and a short. You may need it one day.
Finally....
6. Listen to feedback
If someone sends you an email saying "hey, I understand the parameters of your RandomWordGenerator function, but where do you store the string you return? If someone asks you a question, be sure to include something involving that question in your comments. Make your comments so detailed, yet simple, that if your code was viewed by three million people and your email was provided for questions, you would have no unread messages (no, this isn't because nobody loves you, it's because you're comments are flawless).
That's about all I have to say about comment. Please, for your fellow programmers, for your team members, and for yourself, comment your code. I hope you guys do a lot more of it after reading this
1. Know your audience
Think about who will view your code. Are you on a team? If so, think of the information they need to know to do their part.
// This function pans the camera depending on what the user pressed // if the user presses A, the camera pans to the left 15 degrees per second, D pans to the right 15 degrees per second
This is for any of the programmers working with the camera. Perhaps making the cinematics.
2. What purpose does your code provide?
Are you doing this code for your personal use? Maybe your making a program involving Direct2D to reference in any future programs involving Direct2D. In that case, you should use comments to explain why you're using a function or factory. Explain the process so thoroughly that you can look at the program years from now, and be able to recite the steps in your sleep. Is the code to teach beginners? Do the same thing. explain it as if the person reading has no idea what DirectX is. Think of a person who knows nothing of your coding language....keep that guy in your head, and comment, comment, comment.
3. No such thing as too much commenting
Too much commenting is non-existent! Remember: someone reading that code may not know ANYTHING about programming. Or maybe they just don't know anything about whatever you're doing. If someone specializes in Object-Oriented C++ and he's switching over to C#, he can skip a LOT of basics (but not all) so he may go straight to the advanced stuff. You're thinking "if someone's looking this far into C# then he definitely knows his C#" well think again. Gurus of one language may be ignorant and skip ahead in another language to save time. There is, however, such thing as too little.
This would be an introduction for C++ to those who just got through the basics in an intermediate lesson:
//instead of using int main(void) use int main(int argc, char ** argv)
Now I don't know about you guys, but if I was a noob in programming, I'd think "wtf are two star thingies doing there!?" A better introduction for replacing the simple main to the more useful main:
// int main(void) is the main function to startup the program you've probably used up until now // a more optimal version of main would be //int main(int argc, char ** argv) // return value: integer (typically 0 indicating success, depends on the program) // parameters: the integer is the count of arguments(strings) and the second parameter is an array of char pointers (strings)
*Whether you use single line comments or block comments is entirely up to you.*
Was this too much? NO! Was this too little? Perhaps. It largely depends on your audience. You could, for example, further explain the varieties of the return value? You could also explain what exactly arguments are? Maybe explain what this version of main does that the previous version doesn't?
4. Format any way you want
Here are some examples of formatting your comments, using a function I made in a word jumble game
string RandomWordGenerator(hTable &hT_Dict)
/*
FUNCTION BLOCKS -> used to explain a function (I like using these, good for custom functions)
-----------------------------------------------------------------------------------------------------------------------
Purpose: Finds a random word in the dictionary, scrambles it, and uses it in the game
Return: A string that represents the scrambled word
Parameters: a reference to a Hash Table (the dictionary)
-----------------------------------------------------------------------------------------------------------------------
*/
{
STEP MARKS -> used to explain the steps to do a particular task (good for anything that takes a lot of steps to do one thing)
//step 1: create a temporary string to hold the word
string temp;
// step 2: find a random word in the dictionary and set temp equal to the random word
temp = hT_Dict->find(randomblahdyblah);
// step 3: scramble the word
WordScrambler(&temp);
// step 4: return the word
return temp;
}
There are many different ways you can use your comments. You can make them look pretty or fancy, you can put them in a boring paragraph, you can put them in step format, you can put them anywhere you want any way you want. Best rule of thumb is to put them up somewhere the user will definitely not skip over by accident.
5. Comment ALL your work
Don't be stubborn! Saying "this stuff is so easy, how could I ever forget this?" is just ignorant. My uncle graduated as a programming major. Twenty-two years later as a computer engineer, he saw a new job opening in his company involving C programming that paid a lot more. Unfortunately, spending the years playing with hardware instead of programming software doesn't keep that stuff in your head. He didn't even remember what a virtual function was. Typically if you learned something, no matter how long it has been, you can refresh your memory much quicker than you can imagine! But to his horror....he didn't comment when he was learning about virtual functions. OOPS! Comment ALL your work! I cannot stress this enough. Don't be stubborn and ignore commenting that lesson about the difference between an integer and a short. You may need it one day.
Finally....
6. Listen to feedback
If someone sends you an email saying "hey, I understand the parameters of your RandomWordGenerator function, but where do you store the string you return? If someone asks you a question, be sure to include something involving that question in your comments. Make your comments so detailed, yet simple, that if your code was viewed by three million people and your email was provided for questions, you would have no unread messages (no, this isn't because nobody loves you, it's because you're comments are flawless).
That's about all I have to say about comment. Please, for your fellow programmers, for your team members, and for yourself, comment your code. I hope you guys do a lot more of it after reading this
Comments
Note: Please offer only positive, constructive comments - we are looking to promote a positive atmosphere where collaboration is valued above all else.







For learning, it seems like a good way to cement the concepts in your head, which is not a bad thing. But commenting with sweeping generalizations for longer than you need to learn it, just for the sake of commenting a lot, gets tired quickly. I do think too much commenting can be a bad thing. Not commenting is an order of magnitude worse, though.
BUT, the one reason I was hired as an intern and eventually hired permanently at my first company (a month after graduating from Full Sail) was because of the coding practices I had imposed upon myself. They had received many applications from Full Sail, but they told me later a lot of the tests they receive use little to no established 'good coding practices.'
The one thing I disliked about Full Sail's teachers (the labbies especially are guilty of this) was that they didn't teach how to code 'pretty'.I.E. not naming variable 'temp', good white space formatting, and commenting. The general consensus is that it isn't their job, because there is only so much that can be conveyed in 4 hours. They don't get paid nearly enough, and it can be a stressful job without the added burden of telling someone their code is hard to read/understand. They would just grin and bear it, and let the minor bad practices slowly become permanent in the students' heads.
Another point that should be made is that commentary provides knowledge of the code's function when the code is complex. If you ever feel the need to comment code, consider simplifying your code first. Decompose large methods into smaller ones and employ descriptive method and variable names. Only when it cannot be simplified any further should you inject inline commentary, and even then try to focus only on conveying what the code itself can not convey.
string GetRandomWordFromHashTable(HashTable &wordContainer) { // stuff }This function doesn't need comments because it is english and *gasp* it does the same thing as your function!
If you can't name a function saying what it does easily it's probably because it does too much, same with a class.
It is my belief that commenting should only be done within a function definition and only if it would be difficult to read which usually only happens when trying to optimise.
Clean code by Robert C. Martin.
Especially chapter 4 on comments is great reading material
Basically it states that every comment placed in code means that the code that is commented is actually bad code. Good code never needs any comments at all!
Try this and notice how much easier you can find certain pieces of code, just because you don't need to read through all the comments
A little quote:
I do like your article and I think I'm going to start putting some of what you said into practice anyways.
/** * @description find next available entity or return a new one * @return an inactive entity */ ObjectPool.prototype.getNewEntity = function() { // try to find an existing one that is not active for(var i = 0; i < this.entities.length; i++) { if (this.entities[i].bActive == false) return this.entities[i]; } // failing that, insert a new one and return it var newEnt = this.initFunc(this.initData); this.entities.push(newEnt); return newEnt; }WIth your system, this would look like this:
//////////////////////////////////////////// // find the next available entity //////////////////////////////////////////// ObjectPool.prototype.getNewEntity = function() { // step 1: iterate over all the entities using i as an index for(var i = 0; i < this.entities.length; i++) { // step 2: if the entity at position [i] has the property bActive set to false if (this.entities[i].bActive == false) // return the entity return this.entities[i]; } // step 3: call the init function to create a new entity and pass it the data given in the constructor of this object var newEnt = this.initFunc(this.initData); // step 4: insert it to the end of the list this.entities.push(newEnt); // step 5: return the new entity return newEnt; }Note that in the first case, im using autodoc comments - this is actually useful. If people have to navigate to the file containing the source code to read the documentation for a function call, they are losing valuable time.
Commenting every line of a fairly straightforward method is also a waste of time. If somebody does not understand why there is a for loop involved in the process of searching for a thing in a flat list, they have no business reading or changing this code anyway. Furthermore, some methods contain branching (and looping) meaning that numbered steps are meaningless. It is possible that steps 3 and 4 are never executed, in this example; actually thats the common case since an object pool prefers not to allocate new elements.
Note also that your version does not communicate the intent of each section of the function, it communicates basic facts about the language. This is also a waste of time.
Clean Code is an excellent book. Probably not for beginners, but once you've been coding long enough to groan when you look at your own code, it will help you see how not to. In particular, the concept of self documenting code (and unit tests as documentation) have done wonders for my style. If you can read each line of code aloud without feeling foolish you will almost never need to write a comment.
And as for higher-level view on the application - it needs to be described using tests anyway.
I would have written your code example the following way:
string getRandomWordFrom(hTable& dictionary) { string word = dictionary->find(randomWord); scramble(&word); return word; }"Let your code be the comments."and "Let the tests be the documentation."
Comments are reserved for notes and explaining something if it's, for whatever reason, very obscure or, god forbid, hackish. We have autocomplete, descriptive function names are no longer an issue and if you can't explain a function in the reasonable length of a sensible function name anyway, maybe the function itself could do with a redesign.
3. No such thing as too much commenting
"Too much commenting is non-existent!"
Wrong idea, as stated above there's nothing better than self-explanatory code, full stop.
Every line of code in programming is ruled by a single rule: the less, the simpler. There's nothing worse than having to read hundred of lines of code when debugging, looking for a bug or just when trying to understand a source code. That can turn out to be a huge wasted amount of time for both the original writer and the readers.
You guys are most of you native speakers but one of the non-native speaker newbies' common pitfalls when it comes to commenting is to translate everything into their native language(s) and/or to repeat exactly the same that what the code already says. Yes commenting a "for loop" or a if condition such as "This for loop iterates through the array" is completely meaningless and highly deprecated.
4. Format any way you want
Well yes and no actually.
If you're yourself a comment-freak then you MUST not format any way you want but you should rather use Doxygen which would provide you powerful automated output formatting for your documentation.
I'd replace that chapter with some helpful links to Doxygen API.
5. Comment ALL your work
Well sorry for your uncle but your example is typically wrong and somehow has nothing to do with code commenting. So following your advise in this case why not to provide the whole K&R every time you're writing a template method, a callback, a for loop, a variable (this is an integer and usually -depending on which architecture you're running on- it can be 32-bit long).
Here again this is the typical newbie mistake which consists in commenting every line by repeating exactly the same that what the code already says.
You don't comment all your work (unless again you're asked to deliver a third-part API and then you should use Doxygen). You comment when it's needed, that's all. And before commenting something you should ask yourself twice whether you'd better not refactor those lines of code first.
I'd replace 3. and 4. with those one: Comment when it's needed -> self-explanatory code always prevails on commenting -> Consider refactoring or cleaning your code more than 2 seconds before commenting anything (that IS real maintenance)
To make it short, I wouldn't recommend that article for now...
Good code is easy to read and self explanatory and does not need allot comments to explain its purpose. In cases where code would need comments to explain it's workings you might think twice before writing it. Add to this the fact that if anybody is going to mess with this code they should have a certain level of understanding of the language and project it self .Since we are not all super star programmers with uber skills that let us write code that only we understand this should be fine for majority of programmers.
They only cases where I think comments should be used are
- Code written is so complex that it cannot be described in pseudo code (re factoring this might be better idea )
- You are writing a library that has to be used by other programmers. In this case I would say commenting would be mandatory and you should keep you comment format consisted, preferably use a standard so you can generate documentation out of it as Tbop mention before.
- You are using some fancy language specific exploit that is not well know, showing off your well profound leetness
- You are doing some sort of quick and dirty hard coding fixture / hack showing off you lack of leetness or time to resolve the problem properly.
In my years of experience found that when ever I had to debug an application because of a bug request. The bug was found where people documenting the most. So there seem to be a correlation between commented code and bugs. My guess is that good programmers naturally know when they are in need to explain their fuzzy code ;)
I also agree that your code itself should be the best documentation. Appropriate function names, proper variable names, coding conventions, etc., are what makes code readable. E.g., a function's name should describe exactly what it does... it should also only be doing one thing -- if it does more than one thing, it's time to split the function and make it easier to read.
Agreed on another point -- programmers should avoid using 'just any formatting'. I'd highly recommend using a commenting style that you can run through a documentation generator like Doxygen. It makes documentation very easy (spit out a web page or help file) and keeps comments generally consistent. Additionally, I try to avoid too much 'pretty printing' formatting because it really does take up too much time and adds to maintenance overhead. The only time I use text 'lines' in comments is at file headers to put in a copyright or license disclaimer or some such and that's about it.
I tend to reserve comments for function descriptions using Doxygen formatting, describing the function at its most basic level and any assumptions that it makes. When I do comment code, it's usually because I'm noting down assumptions made in the code or because I'm clarifying obscure code (aka, bad code). Most of the time when I find the need to comment code because it's 'tricky', I think about it for awhile and rewrite the code so that it's not tricky. Tricky code is almost always bad code.
I also, as another commentor mentioned, use comments to explain design decisions. It helps when code is understandable but the reader is thinking "Why the HELL would they do it this way???" to explain in plain english the decision behind the design.
Anyway, 'nough said I think...
In most cases I agree, but there are times when the code makes assumptions about what it's getting that won't be clear when simply reading the code no matter how good (or bad) it is.
However, that being said, this article made me shudder. In essence, what the author is saying is equivalent to me writing a novel and including dictionary entries for each word in a paragraph prior to the paragraph for EVERY paragraph in the book. Doing this so that a reader that is new to English can better understand my novel is admirable, but I am writing the book with English readers in mind. For those readers the added information is disruptive, unnecessary and irritating. I expect, and rightly so, that if the reader is new to English they will learn on their own via their own means.
I have encountered much code in my time commented as in the article and I find it infuriating. I have spent countless hours removing unnecessary comments from code just so that I could actually read the darn code!
I taught myself how to read code. Barring assembly language, I can pretty much make out what is going on in the code, so long as the function and variable names are verbose and in English, even if I do not know the programming language. It is not too much to expect that the reader will be somewhat familiar with the language in question. Unless the programmer is writing the code to teach the language, there is simply no need for such verbose commenting.
I am not saying comments are unnecessary, but comment to describe the overall function if it is not apparent or does the unexpected. Don't tell me that "return 0;" returns 0.
Comments are a failure to express yourself completely in code, and you most certainly should not comment all your code.
Comments rot. Comments lie. Comments mislead. Comments obscure the true meaning of the code.
The best comment is a deleted comment.
I agree that this article could be "misleading" as it could be seen as a reinforcement of bad habits but to be honest I've found over the years that these "bad habits" are only bad when viewed by other people. I've commented things my way, and it's driven people mad as much as it's been for me to deal with other people's commenting habits. When working on a team you generally fall into whatever commenting guidelines drive that team, when working alone you do whatever you want. So commenting is a very subjective thing and an argument that's been ongoing since the dawn of programming.
For further reading on the whole debate, here are several hundred opinions on the matter in a thread I started back in 2000.
The best comment is a deleted comment? I think that's a bit of nonsense.. Comments can describe a large chunk of code without having to mentally compile it and figure out what is going on. I just think people shouldn't get overzealous with how liberally they comment.