Introduction

Commenting your code is like cleaning your bathroom—you never want to do it, but it really does create a more pleasant experience for you and your guests. Because I’ve recently adopted a new mantra to use comments frequently and appropriately in my code, I spent a few hours researching the literature on commenting readability, reusability, and guidelines.

HTML Form Builder

It was a bit overwhelming to see the sheer amount of information and discussions on the topic. Basically, there are a lot of tough, but fundamental questions out there like what does “frequently and appropriately” mean? Because there are a million different beliefs and contradictions on the subject, I created this brief overview to present my findings.

Types of Comments

Code Commenting - This refers to writing descriptive variable names that are self explanatory. This is a minimalist form of commenting, and looks like this:

function addUserToDatabase(userName, userAge)

Without any additional information, you can tell that the function will add a user’s name and age to a database. A common implementation of this is called Hungarian Notation.

Inline Commenting - Specifically, these types of comments come at the end of a line of code, but we can also use this term to refer to comments inside of a function as well. This is the most basic form of commenting.

function calculateHitPoints(cUser) {
    var nStrength = document.getElementById("enemyStrength").value; // grab current enemy strength    // subtract user size : small = 1, medium = 2, large = 3
    var nDamage = (nStrength * 3) � cUser.nSize;
    return cUser.nCurrentHitPoints � nDamage;
}

Function Commenting - This type of commenting is found on the lines above a function, and reveals all of the necessary details about that function. This includes parameters, return values, and any logic quirks or decisions that were made:

/*
 * Summary:      Calculate hitpoints after attack using formula
 *               new = current � ((enemyStrength*3) � size)
 * Parameters:   cUser � object containing hero's stats
 * Return:       Boolean indicating life or death
 */
function calculateHitPoints(cUser) {
    �
} // end calculateHitPoints

Class / Page Commenting - Comments that refer to an entire page or top level object fall into this category. Usually these comments include a broad overview, last edit date, associated files, author, and contact information. Additionally, this may include a general footer at the bottom of every page. Kevin wrote some great templates for building these types of comments in his feature on using XHTML templates.

/* 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - Title : 
Author : 
URL : Description : Created : 
Modified : - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
*/

Commenting Regulars

When developing in a team environment, standardized ways of indicating the next step in the process are great ways of communicating to other programmers and making the entire process efficient. These are also known as functional comments.

[Functional Comments] serve one purpose: adding functionality to the development process.

Bernhard Spuida · The Fine Art of Commenting

They don’t tell you anything about the code, but they do provide documentation on what needs to be done as well as what has been done. Here are some common comments you can feel comfortable using in your code:

  • TODO: This key phrase signifies what needs to be accomplished and should be placed on the line where the future code should go. Some development environments recognize this phrase and will create a to-do list off of it.

  • BUG / FIX: Document a specific bug, or a fix for a bug, and place the comment above the line it pertains to. If you use bug tracking software, include the ID of the bug, so you can always track where it occurred and how you fixed it.

  • TEAMNAME: This comment is usually different wherever you work, but is used to call attention to a certain programmer or programming team. For example, you may want to let the Artificial Intelligence team know why you made a certain decision and so you would use this type of comment to alert them. Read more about this in The Art of Code Documentation by Drew Sikora.

In addition to commenting keywords, there are programs out there that will document your code based on standard comments. While relying on these programs leaves room for error, they are still worth taking a look at. Briefly, two types are XML Comments and JavaDoc

Increasing Comment Readability

In a perfect world, reading code would be like reading a book. Unfortunately, code is written for computers to execute, not for humans to read. You can’t just read code from start to finish—they’re like those choose-your-own-ending books, forcing you to go all over the place to figure out how not to kill your main character. Comments are a great tool for adding context to your code, so that when you jump around you know where you are. With that in mind, here are some tips to make your code easier to read:

Commented Paragraphs � Write your code and comments in paragraph format. In 10 Essential Development Practices, Damian Conway suggests that we should, “Break each piece of code into sequences that achieve a single task.”

Precede comments by a blank line � Doing this creates a distinct separation between your code and comments. Plus, it’s visually pleasing.

Properly tab comments � Make sure comments are tabbed out to the line they are referencing. Additionally, make sure similar comment types align when tabbed. Here’s an example:

var MAX_USERS = 2           //all players
var MAX_POINTS = 100000     //needed to win game

Don’t insult anyone’s intelligence � All commenting is not productive commenting. Too many comments can make your code less meaningful and therefore less readable. An example:

for(i = 0; i < object.length; i++) { //loop until i hits max length

It’s not design � I see a lot of people use crazy characters all over the place and it’s really not necessary. More often than not, it distracts from the business at hand. Keep it simple, keep it sweet.

Create a consistent style � There are many beliefs on the proper way to comment code. Some feel comments should be so detailed that a non programmer could follow the logic, while others believe you use comments for support. What matters most, I think, is that you are consistent in your commenting style. This helps your reader know what to expect when going through several different projects.

Comment while you code - The chances of you commenting a finished project are slim, so do yourself a favor and comment your code immediately.

It is a good practice to write comments at the same time (or earlier than) you write your code.

MSDN · Using Comments Effectively

Commenting while you code forces you to make sure your logic “sounds right.” Plus, your comments are going to be more accurate when the understanding of what’s going on behind-the-scenes is fresh in your mind.

Reusability in Comments

The most interesting concept I came across while reading about code commenting is “comment reusability.” This is something we think about all the time when writing markup and CSS to minimize the amount of work that needs to be done when changes are made. Same principle works wonderfully when it comes to commenting. Here’s an example: Imagine that we have a textbox that’s being edited:

document.getElementById("myTextbox").style.width = "100px"; // change textbox width

The simple comment in that line is not reusable. What if we were to change the textbox to a select element? We would have to change the comment as well. While looking over some coding practices, I came across another question: Is it acceptable to comment the end of a code block, like this:

function calculateHitPoints(cUser) {
�
}  // end calculateHitPoints

I’m split down the middle on this one. With modern text editors that draw lines based on your tabbing, I would not comment the end of every code block. I do, however, see the benefits of commenting the end of a function. Functions usually remain in place, but logic blocks switch around often until bugs are ironed out. Because there are usually a good number of code blocks in a document, the commenting can get pretty heavy without adding a lot of new and useful information.

Speaking of function commenting, Cprogramming.com produced The Hows and Whys of Commenting, which stresses the importance of reusable variable names in functions. They use an example of a funciton that calculates speed. Instead of declaring the function like this:

function getSpeed(runnerDistance, runnerTime)

You should make it reusable by naming the variables generically:

function getSpeed(totalDistance, totalTime)

By doing so, you can logically calculate the distance for any object, such as a plane, car, train, and not just that of a runner.

Now, when it comes to using Hungarian Notation, I want to point out that the topic is a bit controversial, stirring up quite a few heated debates. The Good, The Bad and The Ugly believe it is inefficient to change the variable name every time you change the variable type. For example, ‘szEventType’ should not need to be changed to ‘nEventType’ if you decide to make it an integer rather than a string.

Regardless of you decide to do it, try to remember to take reusability in your comments into consideration. The more reusable the comments, the less time you’re going to spend dealing with them. More importantly, when a team member comes along and makes changes to the code, hopefully, he won’t have to browse through all the comments looking for what to change.

Why Bother?

One of the hardest hurdles in commenting code is convincing yourself to do it, so it is important to look to other sources for motivation.

Prior, clear, and extensive documentation is a key element in creating software that can survive and adapt.

Jef Raskin · Comments Are More Important Than Code.

On a more personal note, after I applied my findings to some of my recent projects, I noticed some significant improvements to my programming lifestyle:

  • I was writing better code. By commenting everything, I was forced to think about why I was doing something rather than just making it work. I was programming smarter rather than harder. Because commenting my code forced me to verbalize my logic and make me think twice about a line of action when putting it into words, I usually found ways to optimize my code when it didn’t “sound right” to me. The comments lead to increased optimization and ultimately less work. Had I gone through after I finished a project to explain things, I’m positive I would have wasted a lot of time reprogramming and recommending bad logic. Time will tell if it decreased bugs as well.

  • I was improving the future. You never know who’s going to be looking at your code or when you’ll need to refer back to it. Future Ryan, my co-workers, potential employers and even my mom are really going to appreciate my commenting investment, because it’s going to save them time. Time is money (especially in programming) and so shaving off time wasted on confusion and interpretation is definitely worth the effort.

  • I was proud of my work. One of my biggest problems I have in my life is working on the same thing day in and day out. If I’m proud of what I doing, it basically removes that mental block. Because my projects were clean, flexible, efficient and sexy, I really enjoyed coming back to them and that, to me, is something priceless. Also, it makes it a lot easier to give a great first impression to job applicants, investors or even obsessive-compulsive blog readers when the code was created in a professional and consistent manner.

See For Yourself

I’ve written a simple JavaScript function to illustrate how even if you think all of the comments seem important, bad commenting decisions can hurt the readability of your code. Here is the result:

//-+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_-
// I wrote this script to process a battle between two units.  
// The attack member functions do the calculation, but this
// function determines the order of attacks.
// Two valid objects must be passed in, and then the function
// will return true if everything worked ok. 
//-+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_-
function beginBattle(attacker, defender) {
    var b; // boolean to hold life or death
    var teamCount; // counter for loops
    if(defender.agility > attacker.agility) {
        b = defender.attack(attacker);
    }
    // if there was a previous strike, make sure he is still alive then process the attack
    if(b) {
        b = attacker.attack(defender);
    }
    // see if any teammates want to counter attack
    // loop through the defenders teamates starting at i = 0
    for(teamCount = 0; teamCount < defender.team.length; i++) {
        var teammate = defender.team[teamCount];    //individual teammate
        if(teammate.counterAttack = 1) { // 1 means they have counter attack enabled
            b = teammate.attack(attacker);
        }
    }   
    // make sure that somewhere in here death processing is handled.
    return true;
} // end function

It’s not terrible, but it could be better. Using the exact same function, we’ll apply some of the commenting guidelines I talked about above:

/*
 * Summary:     Determine order of attacks, and process each battle
 * Parameters:  Creature object representing attacker | Creature object representing defender
 * Return:      Boolean indicating successful fight
 * Author:      Ryan Campbell
 */
function beginBattle(attacker, defender) {
    var isAlive;    // Boolean inidicating life or death after attack
    var teamCount;  // Loop counter    // Check for pre-emptive strike
    if(defender.agility > attacker.agility) {
        isAlive = defender.attack(attacker);
    }    // Continue original attack if still alive
    if(isAlive) {
        isAlive = attacker.attack(defender);
    }    // See if any of the defenders teammates wish to counter attack
    for(teamCount = 0; teamCount < defender.team.length; i++) {
        var teammate = defender.team[teamCount];
        if(teammate.counterAttack = 1) {
            isAlive = teammate.attack(attacker);
        }
    }       // TODO: Process the logic that handles attacker or defender deaths    return true;
} // End beginBattle

In my opinion, the code has become much more pleasant to read with only minimal changes. First, we applied some consistency. All of the comments have a blank line above them, start with a capital letter, and are tabbed properly. Next, variables such as ‘b’ were changed to ‘isAlive’ to make them self explanatory. Lastly, a ‘TODO:’ was added to make future changes stand out. By using brief and consistent pieces of language, I’ve significantly improved the readability of my code.

Build Your Own Style

Now, there is an entire movement of programmers out there that believe that code is essentially another form of personal expression and so it’s important for me to stress that I am not suggesting that these ideas and strategies are the only way to explain your code. Instead, I want people to walk away understanding that comments are important because they can affect the readability, performance and professionalism of your programming. I highly recommend that everyone take some time to reflect upon and create commenting guidelines based on what you find is important and necessary for your situation.

If you want to find more information on this topic, I suggest reading all of the articles I’ve linked to throughout this essay. And while I have not read it myself, I have heard many good things about Literate Progamming by Donald E. Knuth. As always, if you have any good ideas about commenting code, let us know because we always like to hear.

HTML Form Builder
Ryan Campbell

Successful Strategies for Commenting Code by Ryan Campbell

This entry was posted 5 years ago and was filed under Features.
Comments are currently closed.

· 112 Comments! ·

  1. Yannick L. · 5 years ago

    Once again a really nice article. I’ve always had a problem commenting my code nicely (yeah I know you’d think it would be the easiest thing). This article will go a long way to helping me comment my code better.

    Thanks again.

  2. Colin D. Devroe · 5 years ago

    I’ve always had a problem with commenting code while I’m programming. I think its because my apps go in different directions while I’m programming - I am not really sure where I am going to go next. At least that is the case in the very beginning of a project.

    If I’m programming a specific function or class I can usually see the future and comment accordingly. Otherwise I’m always stuck going back and commenting after the block of code is complete.

  3. Kevin Hale · 5 years ago

    Dude, I love the Goofus/Gallant example functions. Good times.

  4. Scott Manning · 5 years ago

    Fantastic article. I comment every piece of code I write. It helps me and it of course helps those who will contine on a project I started.

    I just wish more people had this mindset.

  5. Rei · 5 years ago

    What’s up with the “i++” in your last two code examples? That was a lot more confusing than the comments ;)

  6. Augusto · 5 years ago

    I really hate people who put verbose idiotic comments in code.

    // We’re going to add a bonus to the player’s score score += getBonus();

    And when people are fixing bugs, I’ve found a bunch that like to put the bug id and announce they’re going to “fix” the problem with too much fanfare.

    // Begin fixing BUGID #132134343

    // This bug was caused because somebody decided to // add hard code the amount of bonus points // when you find the secret item. // We found the solution to be to just call // the getBonus() method, and it should all work now // — Doofus

    score += getBonus();

    // End finxing BUGID #132134343

  7. Doug · 5 years ago

    I’ll throw in some disagreement about a couple of things. Code commenting has one purpose: to communicate to a developer at some time in the future how some code works, so that he can adapt/fix it.

    Hungarian notation is bad because it discourages descriptive naming. By forcing you to add extra characters to a name indicating type, you decrease the likelyhood that you’ll use a long descriptive name, and you don’t add any information: type information is already available in the variable declaration. Worse, if you do change types, and don’t change the variable signature, then you’re potentially introducing misleading information.

    Likewise, end of function tags are bad because they can be misleading, and they don’t add information that is not available from brace structure (and in any reasonable modern editor, you can easily reformat all text to correct brace indentation).

    Similarly, excessive inline commenting can lead to readability problems: if you have too many comments, how do you tell when the author is trying to communicate something important? For example I consider:

    // Continue original attack if still alive
    if(isAlive) {
        isAlive = attacker.attack(defender);
    }
    

    A bad comment. It’s essentially documenting the usage of the if conditional. The if conditional is self explicit. If there is something interesting about the logic of doing this, perhaps it ought to be code explicit instead:

    if(isAlive) {
        isAlive = attacker.continueAttack(defender);
    }
    

    Also, for your header comments, you’d be very smart to adopt javadoc compatibility, even for c/c++ code. There are lots of tools that make that a smart move.

  8. Joe Crowe · 5 years ago

    Good article. However, I am of the opinion that the use of tabs rather than spaces in code contributes to problems when tabstop values vary. Tabs made more sense when the price of storage was higher.

  9. xyz · 5 years ago

    Also adding BUG Numbers to code makes it look clumsy if you have a good versioning system. Imagine code after x number of bugs are fixed. Unless you are adding some code which is really weird( and ponts to some vague requirement or “special” customer request ), the comment only should only indicate what the code does rather than what bug it fixes.

  10. Bob Smith · 5 years ago

    I think you’re a little off the mark. The most important thing to comment in any program is the meaning and use of the variables. A programmer can see what a program does by looking at the code, but he can not easily infer what a variable means. If I can get the big picture from the block comments and the meaning of the variables from their comments, the code is almost always easy to follow.

  11. Thomas Stigsen · 5 years ago

    Great article! …just got one point. I hate TODO’s When you allow developers to decorate faulty code with TODO, instead of fixing it…it’ll just never get fixed. Fixing the code right away is far less expensive than waiting for a system test to catch the error…or a poor end user. Whenever I see a TODO tag on a method, I get the shivers, do this method work at all… Don’t do TODO

  12. Dave Jarvis · 5 years ago

    I see two minor issues with the code:

    1. Side comments. Even though they look nice when aligned, they become a time sink to keep aligned when you have to rework the variables. I prefer to keep them on top:

    // @Boolean indicating life or death after attack@ @var isAlive@;

    1. End comments. Generally speaking, these are pointless, especially with IDEs that clearly mark the beginning and end of a method. Also, since large methods should be no more than 20 - 30 lines, the start and end braces are always visible and easy to spot (with proper indentation). Thus:

    } // @End beginBattle@

    Should read, simply:

    }

    This also eliminates another maintenance burden for when the name of the method is refactored. Also, it is one less thing to remember, and one less thing with which the code is cluttered.

  13. Grimen · 5 years ago

    I like the style stuff. I think it’s valuable to consider process-wise how and when you add comments.

    1) I add comments when there is lore that a future programmer is unlikely to know (ie weird HW stuff or reference material). I comment when the algorithm is complicated or there are subtleties to the code that I think might be missed.

    2) I add comments when I’m explaining anything for someone reviewing my changes. If the reviewer is versed in the technology but unfamiliar with the actual change then commenting where the reviewer needed help with is often the best way to cover what a future engineer will need to know. This doesn’t work quite as well for extreme-coding style becuase both folks know the change too well. Best to ask someone who wasn’t making the change to review.

    3) I add comments when I’m reading the code later and I have to stop and figure something out; if it’s not obvious to the author 6-months later then it’s not going to be obvious to anyone else either.

    4) Too many comments start to hide the code. An editor that understand color can help; setting the comment color to be similar to the background color (I like a light pink on a white background) lets you see the code clearly and the comments as needed.

  14. Old_Bob2 · 5 years ago

    I have only been coding since 1989, so I am far from a “veteran”. I am of the opinion that Tab characters are O-U-T! No Tabs, EVER, in source code. Personally, I find Hungarian Notation irritating, and as others have said, it provides little-to-no useful information, and should be avoided.

    Lastly, and quite honestly, a bigger “difference” between my coding style and what, evidently, is considered “accepted” is the positioning of braces.

    I really don’t like it when the braces align as follows:

    if (isAlive) { isAlive = attacker.attack(defender) }

    When I code, I indent two spaces (no tabs), and the begin brace aligns with the end brace, and each statement they surround are aligned with them.

    For example: if (isAlive) { isAlive = attacker.attack(defender) }

    Fortunately, this actually displays correctly when using a fixed-width font (which is what my text editor displays)

  15. Joshua Olson · 5 years ago

    I just wanted to share a technique that works for me. Maybe it’ll work for you too. When I build a function, it generally starts something like this:

    function ProcessRequest(Player p, Action a) { // Step 1. Validate request // Step 2. Create local variables // Step 3. Collect object rules for evaluation // Step 4. Perform action on Player object // Step 5. Update Player statistics // Step 6. Destroy all local variables }

    Then, I fill in the function body between the comments I just created. With minimal effort, the basic commenting is complete and the function logic was “flowcharted”. This really works well in most cases.

  16. Rob Sartin · 5 years ago

    On the use of TODO comments:

    One place I worked, we allowed TODO comments, but had source control pre-commit rules that disallowed merging code into the mainline if it had any TODO comments. When it worked well, this encouraged developers to check in code on a branch that was not yet complete, and merge it to the main line only when it was fully functional. When it worked poorly, there were a few individuals who would just edit the code deleting the undone TODO comments.

  17. none · 5 years ago

    Speaking of Huhngarian notation, having to change the variable name when the type changes is a feature, not a bug.

    Think for instance how easy is to change the type of “i” from int to short or unsigned. This may introduce overflows that will not be noticed until it’s too late.

    In fact, the right thing to do would be to change variable’s names when the semantics of the variable change, including type changes. And the same can be applied to functions.

  18. guido · 5 years ago

    I think I found a little bug in your code :D

    You wrote

    if(teammate.counterAttack = 1) { … }

    which should ofcourse have a ‘==’ …

    :D

  19. alex · 5 years ago

    If you read the original hungarian notation paper (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnvs600/html/HungaNotat.asp) you’ll see that the idea wasn’t to put specific type information with each variable, but to explain how the variable should be used. This is why we have both c (count) and i (index) as prefixes even though both are typically going to be unsigned integers. Sadly a lot of code (including the Windows APIs) get this wrong and put specific type information such as using dw instead of DWORD. Finally there are some hungarian features like m_ for member variables and g_ for global variables that are incredibly useful.

    Kevin Hale said that writing comments while writing his code didn’t work because he didn’t know which direction his code would go in. Kevin: Have you considered writing design documents before hand? These don’t need to be formal, but they’ll help you figure out the structure and can often weed out major issues before you start writing the code.

  20. Ray Ingles · 5 years ago

    Um, am I missing something? In your sample code, you’re testing and indexing on “teamCount” but incrementing “i”. How does this ever terminate?

  21. gjg · 5 years ago

    Good article! Although tedious at times, I’ve always been a fan of JavaDoc comments; the ability to have your code ‘translated’ into Java API-like format is very useful for both the coder and any previous developers. I do agree, however, that commenting functions that are obvious should be avoid, such as the “continue attacking if alive” example above. That should go along with not insulting anyone’s intelligence.

  22. MikeMontana@Hotmail.com · 5 years ago

    My opinions:

    1. Inline-comments should be added when the statement’s impact isnt obvious from the code. For example:

    Something simplistic in appearance:

    if(objDataSet.Refresh()) …

    would greatly improve debugging with :

    if(objDataSet.Refresh()) //intentionally dump pending changes

    1. Commenting bug fixes is a great idea. It greatly helps to see a comment like “// 7/20/04 MM - #192 BEGIN”. Now I know who to ask about any effects, and if I really want to know why it was tweaked, I can go look up the issue #. There’s no need to repeat the Issue-Report - a short terse summary works for me. Its nice to see a BEGIN/END comment block around a section of code that has been tweaked. For a single line statement it would be a waste.
  23. Mark Bullock · 5 years ago

    Consider writing all the comments for a class/file/function/module before writing any code. That way, the comments will stand on their own.

  24. Robert Love · 5 years ago

    Sometimes you write code that well works but you really don’t like it. It should be changed but your current schedule does not really permit it. When this occurs I add the following types of comments:

    //WART: Linear search here is too slow.

    //WART: What was I thinking…. Refactor this method to be more readable.

    Then when time permits, its easy to go find your warts and fix them.

    WARTS are not really bugs but if resolved will improve the life span of the software.

  25. Steve Pavarno · 5 years ago

    I’ve found tools like doxygen (http://www.doxygen.org), JavaDoc, phpDocumentor of huge assistance. I use one of them on almost every project now. Doxygen is an automated documentation extraction tool that requires a specific set of documentation tags for each function and variable (you can tell it to warn you if they are not present). So your function headers have a standard format, but also serve a second purpose: allowing html, latex, pdf, or chm documentation to be automatically generated by parsing your code. Doxygen automatically builds todo and bug lists, class hierarchies and much more. I’ve found that managers are almost always impressed when you show them the auto-generated html created by doxygen: it looks like you have done an impressive amount of work to create this documentation, but really you got it for “free” simply by being a little disciplined in your commenting style, and using a tool to extract those comments to html. Instant “brownie points”! Heh heh! Thanks for your helpful article. I will refer many people to it.

  26. Eric Moritz · 5 years ago

    I just wanted to add a pointer to the commenter, Colin D. Devroe. The way you described your coding style reminds me of how I coded when I was just starting out. It took me a long time to figure out that sitting down, hacking away and letting the functionality expand organically gave me many headaches. Generally how I write comments is like this. I write out the comments first as psuedo code. this will satisfy your hacker instinct to just sit down and code. It also does a few other things. First, it allows you to think things through without much effort. This cuts down bugs substantially. Second, it enables you to comment your code without much effort. By the time you’re done writting the actual code, the comments are already there and you’re done.
    I hope this helps

  27. Lodragan · 5 years ago

    One Item you did not mention was the idea of imbedding documentation in your code. For example tools such as ‘perldoc’ allow you extract imbedded formatted documentation in perl applications.

    I use these capabilities when a language supports them. I built a recent general purpose command line application in perl that not only included general command line help, but also included the complete user and developer reference documentation inside the script - extractable via a command line option in the script itself. The big benefit is it made syncronization of documentation and code a no-brainer, as every change goes into the version control system together.

    For other languages that may not support the automated extraction of such information, you can create your own system (perhaps based on some standard - I am kind of partial to XML myself) that you can imbed in the allowed comment constructs. You would then build your own application to extract this documentation from the code file (perhaps even mapping a simple brevity format to XML etc…maybe there are other options I’ve not anticipated)

    This is a creative possibility that could make your code literally self documenting.

  28. Komojo · 5 years ago

    I’d just like to say, I vote for tabs instead of spaces. No real reason other than it’s faster; I can move forward or backwards one tab width by pressing left or right once instead of four/eight times, and it’s easier to un-tab something by pressing backspace/delete only once. Compatability isn’t a big issue for me; I only convert the tabs to spaces if I’m pasting something into a document or printing it out.

    Recently I’ve started writing dates down every time I make a significant change in my code. Similar to what Mr. Aquino said. My function headers all look like this:

    /*********************************************\

    Circle contstructor

    Purpose: Create a circle with a specific radius and color Parameters: —Radius: Radius of the circle —Color: Color of the circle, in {etc} format. Returns: Nothing ———————————————————————— Komojo 7-31-2005: Created Komojo 8-1-2005: Added “Color” parameter \*********************************************/ Circle::Circle (float Radius, RGBetc Color) { … }

    It’s especially helpful if you have more than one person modifying a single function for some reason.

  29. Roberto · 5 years ago

    MikeMontana: Wrong, commenting bug fixes is a terrible idea, and it gets more terrible when you are on the tenth iteration of a system and you see comments pertaining to a fix that was made ten years ago for code that isn’t even there anymore. The bug is gone, the code and its comments should stand on their own. If you need to know who to blame that’s what version control is for. If you must know the bug #, look it up in the revision control system check in comment.

  30. bill · 5 years ago

    Nice article. Commenting is important and often overlooked. Unfortunately it’s also overworked.

    1) Type descriptors If you use type descriptors and change a variable’s type you had better change the type descriptor to match the type, otherwise you should just drop type descriptors altogether. E.g. szUser indicates that User is a null-terminated string. If you change the type of User to integer, you had better either rename the variable to iUser or just give up on Hungarian notation (which might not be a bad idea anyway).

    2) End-of-block comments There are times when commenting the end of a block helps sort out what some chunk of code is doing. It makes less sense to comment the end of a block that is either not nested or is otherwise patently obvious.

    3) Descriptive Variable Names I would ten times rather work with code that uses “i” as a loop iterator than some mumbo jumbo variable called “theLoopIterator.” Rules like using descriptive variable names are good in general, but taken to extremes, they are just silly.

  31. Ryan Campbell · 5 years ago

    Thanks for the feedback everyone. When the site settles down a bit, I will update the article to eliminate the errors pointed out.

  32. Cade Roux · 5 years ago

    While MS may have misinterpreted hungarian notation in their API use of dw for DWORD - BUT they were documenting an interface which COULDN’T change - so it still serves a purpose for people implementing against an interface. It makes it easier to develop against a vast API like the Win32 API.

    So for fixed interfaces, hungarian notation which are tied to specific types can still be useful.

    For code to be evolved and maintained, not so good - even when properly decoupled from specific types as hungarian notation is meant to do.

  33. ellem · 5 years ago

    Way back when, when I was a Sys Admin instead of PHB, I got code reviewed. Mostly I got picked on for writing “Boring, Obvious, Over-commented” code. I left that company for a lot of reasons but that “code-review” was one of them. The whole thing is documented at Perl Monks here.

  34. bob dob · 5 years ago

    Let the version manager do its job and leave the tracking id’s out of the code. Don’t be afraid to do your homework before fixing the problem. You might even find that backing up one version is the best solution to the problem.

  35. Mike Wilson · 5 years ago

    Nice article, thanks. I have been coding since about 1977 and realised the value of comments when I looked at a colleague’s 10 page 8080 assembler listing with no comments whatsoever. In the mid-80s I heard the most useful piece of commenting advice I’ve heard so far, from a CS prof: “comments should say what the program does, not how it does it”. I’ve used that one ever since. I usualy avoid the comment on the same line as code as it’s easy to mess them up when changing things. I prefer a long comment at the top of a block of code rather than smaller comments mixed in with the code. Nicely written code (like your variable name as comment example) is easier to read WITHOUT loads of comments. Comments in code need white space above and below to make them stand clear. In ‘C’, C++ and Java I use this: /* ** Usually a long-ish block of comments ** ahead of a block of code. Many text ** editors and IDEs can cope with ** reformatting this type of comment, ** vim, for example */ I always write my comments as I code except in rare examples with complex logic where I write commets FIRST to get the logic clear, then write the code.

    Thanks again for an interesting article.

  36. gekido · 5 years ago

    TODO: comments also can often end up being out of date very easily, and can result in code that is misleading or improperly commented, which is even worse than being uncommented in the first place.

    I also typically start coding by writing pseudo code of sorts, then when you are actually writing the code itself, the comments are filled in for me already.

    This also works well when writing wrapper ‘stub’ code that will be written later or potentially by someone else - instead of ‘todo’s i write the purpose of the function or code block into the comments - then whoever is actually writing the code can follow the comments later.

    in-house we also enforce doxygen supported comments to ease the creation of documentation.

  37. anonymoose · 5 years ago

    I was told before that commenting is good but not doing it may be helpful also. If you do not comment and use a weird style of coding, no one would understand it. Thus, this gives you job security. Something I heard from friends…..just something to think about. Not necessarily right but a funny reason not to comment.

  38. Nick Loadholtes · 5 years ago

    Thank you for this great article. I’m always trying to sell people on the importance of commenting your code. I’m going to use this article the next time I have a discussion with my boss…

    Also, the points made under the “Why Bother?” section are exactly the reason why I started to comment my code more. By writing comments in the code before and during the coding process I find that I’m able to write better code faster, and to identify logic bugs faster. Knowing that you know and understand what the code is trying to accomplish is priceless.

  39. Roelant · 5 years ago

    Nice article. In my experience, every line of comment saves 5 minutes later on, let alone prevents bugs from ignorance of what earlier written code exactly does.

    I’ve experimented a bit with literate programming (www.literateprogramming.com), but found it only useful for specificly algorithmic complex code; UI or database code gets bloated too much.

    Still, I think you should at least mention that school of thought when it comes to programming. Although not mainstream, its ideas pop up everywhere in the trade, and for the more complex programming tasks, it is a good way of conceptualizing code. And it transcends the boundary between commenting code and commenting on code.

  40. bob dob · 5 years ago

    I should also add…. another important part of having a good commenting strategy is consistency. As long as everyone is kinda commenting the same way, and the same sort of things, then you will know what to look for when trying to fix problems.

    Thanks, there are a lot of good points and this has been a nice afternoon read.

  41. Perl Junkie · 5 years ago

    I agree almost 100% with the original article. Early on in my development career I adopted many of these practices and I feel it’s helped catapult me past hordes of average developers.

    A couple of additional points:

    One could create a precedence of “do’s” and “don’ts” from the list. This is sometimes essential in the game of “tradeoffs” esp. when forced to work on code already written. You can waste a lot of time trying to massage code into your own “style.” I believe the ultimate trump cards are: readability and consistency.

    Also, I would vehemently beg to differ with what I find to be a LARGE contengent of developers that harp “I don’t need to comment this or that when I can read the code and figure it out.”

    Whoa. Think about it. The point of commenting is a readability, instant recognition, psychological thing. Comments are supposed to appeal to another part of your cognative functions. They are meant to keep the amount of time you spend (even subconsciously) “figuring things out” to a MINIMUM if not completely eliminate that time. Anyone that feels otherwise is missing the point and I can guarantee you both experientially and scientifically that those that “needlessly comment code that I can read and figure out” will be more efficent in fresh code development and code maintenance BY FAR. BY FAR.

    To illustrate:

    Make a list of Christmas presents you want to buy for a relative, then make a list of birthday presents you want to buy for a spouse. Or make it a little more diversive… Make one a list of presents and one a list of items to buy for a home fix-er-up project.

    Don’t put a title on the lists and file them in a drawer somewhere for a few days or a week. Come back to the lists later. Can you “figure out” which list is what? Sure. But multiply the amount of time you had to spend “figuring out” your lists by reading the contents, even if fractions of seconds, by hundreds of those kinds of lists in your possession should you chose not to title your “to do” lists or whatever using the same logic (eg. “I can read the list and figure out what list is it.”)

    Code commenting is NO DIFFERENT. Some comments may seem “trivial” but the point of comments is to appeal to another side of your cognative abilities. We make lists and title them so we can easily and quickly without ANY thought identify them. It’s a bit ludicruous in my opinion to claim “I can read the code and figure it out” when the point is to eliminate that time spent.

    Finally, is it me or does anyone else find it at least mildly ironic that this blog software doesn’t break paragraphs with blank lines when people “comment?” It’s so hard to read the comments here!!! :-)

    -pj

  42. Matt Walsh · 5 years ago

    1) Like many things in life, you’ll have success if you can pretend to be either someone else or you in the future.

    With this mindset (gosh, would I understand this mess? Will I understand this mess next year? What would help me?), you will write the exact right amount and type of comments.

    2) I’ve grown to dislike c++ (//) comments. They just don’t stand out. even though it wastes a space, I do this all the time

    /* Get your own arts program! */

    …and I rarely inline comment at all for the same reason…unless it’s some really dense struct kind of thing.

    3) Design variable names for searchability. Pick funny, strange names. Conversely, use names like ‘buf’ and ‘i’ for things you’ll never need to search for.

  43. saigon · 5 years ago

    Hungarian notation is useful only in non-type-checking languages. It made much more sense in C that in C++; especially it makes problem in OOP, where you are encoureged to make new types (i.e. classes). Basically, I gave up using it when I moved to C++.

    Only exceptions are cases where, for instance, you have same value in several formats; typically you have int and you have to change it to string, then i make something like:

    int CharacterPoints; std::string CharacterPointsString; // for display

    Anyway, I had one bug recently that made me wonder about reintroducton of Hungarian prefixes. Bassically code was

    bool RetVal;

    // … some code …

    RetVal = function(arguments); std::cout

  44. Bill Cunningham · 5 years ago

    Eric Moritz, above, makes a good point about commenting first and coding second. Suggested in Steve Maguire’s book “Writing Solid Code.” Steve stresses that code should be commented and then filled in with code. (1993 Microsoft Press, if you’re interested.)

    Most of the bugs introduced by developers are from either not understanding how to get from Point A to Point B or not understanding the language features. Writing good code depends more on how much you understand the problem. If you can relate the problem in simple terms to your kid sister then you’re probably ready to start writing code to implement the solution.

    Code reviews should be conducted often, even before the product is finished. Another pair of eyes looking at the code will reveal where you went astray.

  45. ctanaka · 5 years ago

    Nice article. One of the most irritating things I come across from time to time is when a comment is actually misleading. This is even worse than trivial and useless comments. Hopefully, someone will make the determination that the comment doesn’t match the code and fix the comment or remove it. Otherwise, it is possible for someone else to come along, assume the comment is correct and make code changes baseed on that assumption. Arrgh!.

  46. Bill Kress · 5 years ago

    Great article. Just wanted to chime in about the end of “whatever” comments. Generally I dislike them, but they can be a good way to analyze disfunctional code.

    Most methods should not occupy more than a screen, but if you ever have to scroll in order to see what your end brace matches, you might want to copy the start-brace line and stick it in a comment after the end brace.

    This can be helpful when you are looking at some code where all you see are 3 or 4 layers of close braces intersperced with code and need to figure out why your loops aren’t working.

    Most editors will allow you to close up any given level, but this involves scrolling and may hide the code you are trying to examine.

    Also, when reusing your comments—shouldn’t you be reusing code? You could just as easily place the comment in a new method/function and reference that function.

    The desire to reuse comments should probably be considered a “Bad Code Smell”. Referencing comments in a parent class, however, perfectly valid.

  47. David · 5 years ago

    In reply to Doug much earlier, Hungarian Notation isn’t about carrying the “type” (in the language sense) around with the variable name - it’s about carrying the “type-of-thing” around instead. I.e. many people mistakenly use things like iVar to indicate it’s an integer. Well, as you say, that’s already available since it’s declared as an integer. What HN really means is that you might do something like nVar to indicate it is a “counter”. The confusion happens because people read “type” and confuse that with language Types.

  48. Bryan Conzone · 5 years ago

    I found this article generally pretty good to use as a reference for commenting codes.

    I am not personally 100% with the variable naming standards that are mentioned or with the use of hungarian notation, though you made a good point in saying that variable names should be descriptive and NOT constructed in a way that if their data type were to change in the future (i.e. String strMyVar to Integer nMyVar) it would require the developer to go back and rename the variables prefix to make sense.

    There are a couple spelling / coding issues I have noticed and other users have mentioned in their posts. Though, nothing that can’t be overlooked to understand the point that is trying to be made. This is an article on commenting code, not proper spelling and javascript :-).

    I have to make a comment to the message a few posts back by anonymoose, about not commenting code because of job security. That’s definitely something I have heard before, but, probably one of the worst suggestions I have ever heard. If someones job is really that insecure then they should probably find another :-). Plus, depending on the size of a project your working on, you yourself may not even touch that code for a few months or longer and may not understand what you did when you come back.

    I also think another good side article seperate of this one would be something on different coding tools / code readers that will look through your code and pick out comments like TODO, BUG, FIX, etc. Most major editors already have them built in and it would be interesting to see if anyone is using any other external tools out there.

  49. beny · 5 years ago

    Nice and useful article.

    I had only one question. What about regions? Most of the IDEs let you define regions (#region / #endregion in Visual Studio) to make your code more compact at the first look.

    Are there any directives to use them? Should I enclose every function in regions, or only classes? How should I name regions? etc.

  50. rhobite · 5 years ago

    Your CODE tags don’t wrap, so many of your examples are unreadable. Just thought you might like to know.

  51. Pooly · 5 years ago

    How to make your code look wrong is here : http://www.joelonsoftware.com/articles/Wrong.html So bad Hungarian is wrong, but managed and useful prefix are. And stop trying to use it everywhere, I event knew people who prefix their method !!! char *szGetUserName(char *szLogin) and sz won’t assure you about a null-terminated string neither…

  52. Anonymous Coward · 5 years ago

    Good job on the article.

    and to Mr. Crowe, the reason tab make more sense is because every programmers have his/her own preference of how much ‘space’ to indent code block. I like 3 spaces, while my co-worker like 4 or 5. By using tab consistently, each programmer can adjust their tab size in an editor and be happy.

  53. David B. · 5 years ago

    I really hope more people comment their code because of this article. If only because it increases my chances of coming across some when maintaining other people’s code.

    The only point I’d disagree with is “don’t insult anyone’s intelligence”. Sorry, but I comment the return statement at the end of my routines with “//this is the end of the routine”. It’s a practise I took up after more than once finding other programmers’ bugfixes inserted after the return!

    Perhaps your next article could be on the importance of unit testing?

  54. Kevin Hale · 5 years ago

    Rhobite, it’s actually the pre tag that doesn’t wrap. If you select the text in firefox you can see the rest of it, but it’s not a good story for IE and Safari.

    Anyway, when it comes to showing code with CSS I’ve found it to be a huge pain because I want to preserve the spaces and tabbing used in code examples (hence, why we surround them with pre) but often a lot of things get visually clipped.

    The obvious answer should be just set the overflow to auto and be done with it but in IE the padding set on the pre isn’t rendered as part of the height and so it also generates these ugly vertical scrollbars.

    There are tons of plugins and solutions out there involving textareas and crazy php and etc. but I don’t want to go there just yet. For now, I’m going to set the overflow to auto and bite my teeth through the IE version.

    I am working on a liquid layout of these pages and hoping to offer more options to our readers, but until then : this is my way of saying that YES we KNOW it was clipping and it was bothering us too. Calm down.

  55. Kevin Hale · 5 years ago

    And I just figured it out, what do you know.

    Basically, you can use some css selectors that only work in IE to solve the problem. Here’s what it looks like:

    pre{ overflow:auto; overflow-x:auto; overflow-y:hidden; }

    overflow-x and overflow-y are read by IE and respond appropriately and fix my vertical scrollbar issue. thanks to everyone that nagged me! sweet.

  56. Relapse · 5 years ago

    Very nice comment writeup. I have to add my voice behind the trailing { for openning a block (if (..) { rather than if (..) \n { ). I find it’s the statement I want to look at and that’s fine being indented after. And tabs remain useful, for the poly-developer-indent-count reasons you’ve already specified.

    Have you looked into any of the PHPdocumentor thingies for this? Common code standards being extracted automatically into code-documentation(ish) is quite useful.

    I will add that when we add Bugfix comments, we also add the date the bug was fixed. Redundant with good versioning software, sure, but if people are reading through the code raw it’s good to have the fix dates in the face rather than after a hunt.

  57. Josh · 5 years ago

    Great article and lots of useful supporting links, you have really cleared up the black art of commenting. I really enjoyed this article, cheers!

  58. Tom · 5 years ago

    I agree that you’re not just writing comments for others, you are writing them for “future you”. Though I generally comment my code pretty well, several times I’ve whipped out a quick hack - then I’ll look at it 8 months later and think “what was that guy thinking!?!” :-)

    One important thing to remember - which I’ve learned from hard experience - COMMENTS LIE! right to your face!

    OK, so I’m exaggerating a bit. But code in the thick of development very often outdates the comments quickly. And way too often, someone will change the code in a function, or its parameters, or its entire functionality, without updating the comments. Treat comments always as probably informative, but never as the “last word” on what the code really does.

  59. Tero · 5 years ago

    Write your code to do the work, write your comments to explain why the work is done.

  60. John · 5 years ago

    Reasonably good article. So … code commentary is good. Wow. Would suggest that the author follow his own precepts in the examples (Code Commenting - This refers to writing descriptive variable names that are self explanatory). See Example 1 below. Why bother to comment what ‘b’ does when a reasonably descriptive name would suffice. Now the reader has to do the mental translation everywhere ‘b’ is used (“Hmm, oh yeah! ‘b’ means isAliveOrDead, but is it alive or is dead if true”).

    Another important safety tip, check your code examples before you publish them. In Example 2, the comment “loop through the defenders teamates starting at i = 0” is not only obvious (violating precept Don’t insult anyone’s intelligence – All commenting is not productive commenting), but it’s also wrong (‘i’ is not used as the loop index, teamCount is). I don’t think this code will work.

    I really don’t like adding the type to the variable name (Hungarian notation). IMHO, this really doesn’t add anything to understandability or maintainability, detracts from readability (I think code should be as English-like as possible), and forces tighter coupling to an underlying type.

    Example 1: //-++++++++++++++++++++- // I wrote this script to process a battle between two units.
    // The attack member functions do the calculation, but this // function determines the order of attacks. // Two valid objects must be passed in, and then the function // will return true if everything worked ok. //-++++++++++++++++++++- function beginBattle(attacker, defender) { var b; // boolean to hold life or death

    Example 2: // see if any teammates want to counter attack // loop through the defenders teamates starting at i = 0 for(teamCount = 0; teamCount Reasonably good article. So … code commentary is good. Wow. Would suggest that the author follow his own precepts in the examples (Code Commenting - This refers to writing descriptive variable names that are self explanatory). See Example 1 below. Why bother to comment what ‘b’ does when a reasonably descriptive name would suffice. Now the reader has to do the mental translation everywhere ‘b’ is used (“Hmm, oh yeah! ‘b’ means isAliveOrDead, but is it alive or is dead if true”).

    Another important safety tip, check your code examples before you publish them. In Example 2, the comment “loop through the defenders teamates starting at i = 0” is not only obvious (violating precept Don’t insult anyone’s intelligence – All commenting is not productive commenting), but it’s also wrong (‘i’ is not used as the loop index, teamCount is). I don’t think this code will work.

    I really don’t like adding the type to the variable name (Hungarian notation). IMHO, this really doesn’t add anything to understandability or maintainability, detracts from readability (I think code should be as English-like as possible), and forces tighter coupling to an underlying type.

    Example 1: //-++++++++++++++++++++- // I wrote this script to process a battle between two units.
    // The attack member functions do the calculation, but this // function determines the order of attacks. // Two valid objects must be passed in, and then the function // will return true if everything worked ok. //-++++++++++++++++++++- function beginBattle(attacker, defender) { var b; // boolean to hold life or death

    Example 2: // see if any teammates want to counter attack // loop through the defenders teamates starting at i = 0 for(teamCount = 0; teamCount Reasonably good article. So … code commentary is good. Wow. Would suggest that the author follow his own precepts in the examples (Code Commenting - This refers to writing descriptive variable names that are self explanatory). See Example 1 below. Why bother to comment what ‘b’ does when a reasonably descriptive name would suffice. Now the reader has to do the mental translation everywhere ‘b’ is used (“Hmm, oh yeah! ‘b’ means isAliveOrDead, but is it alive or is dead if true”).

    Another important safety tip, check your code examples before you publish them. In Example 2, the comment “loop through the defenders teamates starting at i = 0” is not only obvious (violating precept Don’t insult anyone’s intelligence – All commenting is not productive commenting), but it’s also wrong (‘i’ is not used as the loop index, teamCount is). I don’t think this code will work.

    I really don’t like adding the type to the variable name (Hungarian notation). IMHO, this really doesn’t add anything to understandability or maintainability, detracts from readability (I think code should be as English-like as possible), and forces tighter coupling to an underlying type.

    Example 1: //-++++++++++++++++++++- // I wrote this script to process a battle between two units.
    // The attack member functions do the calculation, but this // function determines the order of attacks. // Two valid objects must be passed in, and then the function // will return true if everything worked ok. //-++++++++++++++++++++- function beginBattle(attacker, defender) { var b; // boolean to hold life or death

    Example 2: // see if any teammates want to counter attack // loop through the defenders teamates starting at i = 0 for(teamCount = 0; teamCount Reasonably good article. So … code commentary is good. Wow. Would suggest that the author follow his own precepts in the examples (Code Commenting - This refers to writing descriptive variable names that are self explanatory). See Example 1 below. Why bother to comment what ‘b’ does when a reasonably descriptive name would suffice. Now the reader has to do the mental translation everywhere ‘b’ is used (“Hmm, oh yeah! ‘b’ means isAliveOrDead, but is it alive or is dead if true”).

    Another important safety tip, check your code examples before you publish them. In Example 2, the comment “loop through the defenders teamates starting at i = 0” is not only obvious (violating precept Don’t insult anyone’s intelligence – All commenting is not productive commenting), but it’s also wrong (‘i’ is not used as the loop index, teamCount is). I don’t think this code will work.

    I really don’t like adding the type to the variable name (Hungarian notation). IMHO, this really doesn’t add anything to understandability or maintainability, detracts from readability (I think code should be as English-like as possible), and forces tighter coupling to an underlying type.

    Example 1: //-++++++++++++++++++++- // I wrote this script to process a battle between two units.
    // The attack member functions do the calculation, but this // function determines the order of attacks. // Two valid objects must be passed in, and then the function // will return true if everything worked ok. //-++++++++++++++++++++- function beginBattle(attacker, defender) { var b; // boolean to hold life or death

    Example 2: // see if any teammates want to counter attack // loop through the defenders teamates starting at i = 0 for(teamCount = 0; teamCount

  61. Will · 5 years ago

    What you write in comments is frequently good fodder for logger statements, if you have a logging system that works in your intended environment. One thing I sometimes do in Java, rather than TODOs, is to throw a NotYetImplemented exception. The exceptions take me right to where work needs to be done, and they don’t let me defer implementation indefinitely.

  62. Sam · 5 years ago

    I am curious how improving your commenting style is going to make your mother happy.

  63. Ryan Campbell · 5 years ago

    John,

    Those examples you pointed out were put in there showing what NOT to do. In the first example, you see ‘b’ and that is changed in the second example to ‘isAlive’. Looking back atmy article, in the “See For Yourself” section, the first example I gave was what NOT to do, and the second was a correction of the first. Sorry if that was not clear. I was purposefully breaking my own rules to show what happens when you do.

  64. Ryan Campbell · 5 years ago

    Sam,

    My mom is a freqent reader of the site. She doesn’t know how to program, but she loves this stuff.

  65. Larry Albert Rowe · 5 years ago

    My chief issue with most commenting discussions and usage is that it detracts from the work at hand.

    I’ve never seen a comment execute.

    With modern language constructs sensible use of Structure and OO concepts and some of the techniques you’ve described, well named variables, methods, etc. you can get by without writing a book in addition to your executable code.

    However here is a short summary:

    1. Provide sparse extrinsic information that cannot be gleaned from the code because it is by definition not intrinsic to the code.

    2. Use symmetry. That is how you recognize people with one look and that is how you can factor code with one look.

    3. Provide “Programmer’s Notes” in sparse form when you are doing something unusual and not obvious.

    Finally concentrate on the single target function of the code itself and then re-read it twice, and then on the third re-read follow 1,2, 3 above.

    Then move on to the next function.

  66. Jonathan Scott · 5 years ago

    I hate to be too blunt, but I think this article was a particular waste of time. The examples were left wanting, creating the impression the article was entirely self-contradictory. Take the “beginBattle()” function for example; he calls it “beginBattle()” but in his comment proceeds to counter that with “it processes a battle”. Wouldn’t that clue you in to the need to rethink your function names? If your function “beginBattle()” also washes your dog, either you need to do some refactoring, or you need to rename your function to “processBattleAndWashTheDogWhileYoureAtIt()”.

    Another issue: Code is written for HUMAN consumption, not machines. Machines process 0’s and 1’s; not “for”, “if”, and “processBattleAndWashTheDogWhileYoureAtIt()”. If you can get around this idea, and see your code as being for HUMAN consumption, I am sure you can eventually see the argument against unnecessary commenting.

    Writing comments into your code will merely double the amount of maintenance you have to do. Comments WILL become stale and pollute your code. At a minimum, code needs to be compiled, and ultimately tested; comments just hang around not mattering to much of anyone or anything. I’ve seen people trying to fix a bug in a function but only made it worse because the comment was entirely stale.

    Code is created by humans for humans. Compilers translate what we create into something usable on a machine. Comments are for documenting irregularities, and for document parsers like javadoc. You will be a much better programmer if you learn to make more readable code, not better comments.

  67. Sergio · 5 years ago

    I like the article a lot, I agree with the main idea.

    Just a little comment about the tabs and the {}.

    I like tabbing, it is faster than writing several spaces, and it allows anyone to adapt them to their personal preferences using almost any editor (text, IDE, or whatever)

    As for the brackets ({}), I read sometime a good practice:

    If you are using it in a function, just put it below the function definition: void myFunction() {      //code } In any other case, either a loop, or if/case statement, keep it next to the first line: if (a == true){      //code }

    The reason for this was something like: in the former case, the functions can be easily found; in the latter, you save one line of code without decreasing your code readibility, and keeping your lines of code compact inside the big blocks which are the functions/methods.

    I also like another citation: “code is written for humans, and just eventually to be processed by computers”.

    Great article!

  68. Ryan Campbell · 5 years ago

    Jonathan, while you are wrong about this being a waste of time, I appreciate the feedback. Even more so because you spent so much time commenting on a worthless article. Oh, also, your reference to code for HUMAN consumption. My paragraph states that you can’t read code from start to finish like a book. Comments are there to put things into context. Additionally, if you read my entire article you would notice that I state my findings as being ideal for ME, but that all developers should design a style that works for them. Excuse me, I have to go wash my dog now.

  69. Izaak · 5 years ago

    With few exceptions (i.e. you’ve got to do something counter intuitive) I’ve found that if I have to comment code, the code is probably too complex. I think however I’m the only person in the world who feels this way.

  70. Eric · 5 years ago

    This is very informative! I have a class of my own, and I have been trying to find the best way to let them know how and why to comment! I do it well, and that is just out of experience and just because I made it a point to get to the level I am at. I suffered from not commenting as I code, and now I have learned my lesson! Thank you for putting this into a format that is easy to learn and understand.

  71. Izaak · 5 years ago

    I think others will find this very informative: WRT Comment cost benefit

  72. Kevin Hale · 5 years ago

    That’s a really good wiki/link, Izaak. Thanks.

  73. John Galt · 5 years ago

    Well written code needs no comments!

  74. Jonathan · 5 years ago

    I believe that comments should come first.

    // bool ::IsLowerOrderedAttributionAvailable( sCurrentMethod )

    // Iterate over child nodes

    ’ // Skip node if processed or if ==sCurrentMethod

    ’ // Skip node if not hit limit, else return true

    // No other nodes available

    These comments form the skeleton of a function that checks if child nodes are available for attribution of chemicals. There’s no fluff here, and writing the comments out like this makes it easy to see where to put the code. This technique of ‘stepwise refinement’ was all the rage in the seventies with the Algol languages, which lend themselves to this almost conversational style of programming. Thanks Prof Morrison !!

  75. Tadd · 5 years ago

    One simple suggestion on variable naming that has been helpful to me… While Hungarian notation prepends an indicator of type, which I find less useful these days (and I hate “sz” for string — I see that and think “size”!) — I like to prepend an indicator of units. For example: degreesRotation // instead of iRotation secondsElapsed // instead of timeElapsed even pixelsPerSecond // instead of fSpeed (which is all “units”!)

  76. dan · 5 years ago

    for an article on code legibility, I found your html style horrible for reading the code! I had to scroll horizontally for almost every code block. ugh.

    also, this “auto-message-preview” thing is horrible - i can type 60+ wpm but it only outputs 2 wpm.

    aside from that, nice job.

  77. NcF · 5 years ago

    Hey. Awesome tutorial. I’m definately sending this to some people who are beginning programming :)

    Anyways, I hope you don’t mind if I archive this (w/o most of the comments) on my server so I can send a striped down version to buddies. (Will add link to top referencing back to here, naturally)

    -Wes

  78. phil · 5 years ago

    Now if we only know what a “contstructor” is (see earlier message). Part of writing good comments and documentation is learning to write & communicate reasonably well.

    One of the things I fail to understand today is when people say language promotes self-documentation (see: Visual Basic), yet they write the code as though the variable names are homeless vagrants from FORTRAN and use “nam” instead of “name”, “fstnam” instead of firstName”. It’s a couple of extra keystrokes - if you think your code reads well, then make it do so. I have yet to have heard of a coder who claims to type less than 50 wpm in the previous ten years. They lie, but they still claim it. If it’s true, then use that ability.

    I’m a member of one of the DARPA Grand Challenge teams, responsible for organizing data in grids, sent to me by team mates who slurp data from various sensors. When I believe something important is worth looking at, I notify one of my other team mates and tell him to take a peek at it and take a shot at analyzing it, then notifying the Guidance Team if it’s something they need to know about. It’s their choice to determine how to deal with it.

    There’s no need to worry about shorts, ints, longs, as we know we can’t take a chance on overflows for small integer datatypes; i.e. everything which is an integer is a long. (BTW, this is in C++) This also holds for double vs. float when it comes to measuring longitude, latitude, and altitude. Differences aren’t seen until the fifth or sixth decimal place. Things are very easy as a result. The actual grid management is extremely small and sleek. Everything is parameter driven, so I don’t have to worry about the units of longitude, latitude, altitude, etc. The code which interacts in testing (and eventually in production) is responsible for determining some correlation of scale. The exception-checking & -handling is what’s extremely long & careful (by comparison).

    In terms of variables, everything is interacting with the grid internals. Because we have North, South, East, West; West and East are Longitude (obviously) and the first, or ‘x’ subscript, just as the North and South values are the second, and ‘y’ subscripts.

    To ensure everything “reads” correctly, you will always see things such as:

    if (whichCellIsHit > xLongitudeCellCount) {…}

    The point of this is you will always see xLongitude and yLatitude as pairings in the variable names - as a reminder to the type of value you’re looking at and where it falls on the grid. So if you see:

    cell[yLatitude,xLongitude].xLongitudeCenter = …;

    It will obviously be a coding error. I’ve looked at other teams on the project and they’re relying upon “lon” and “lat” - keeping those short, FORTRAN-like, traditional C variable names. I prefer to leave a trail of breadcrumbs which are intuitive to others who are going to have to hate to read my code because it doesn’t match their particular style. The least I can do is make sure the taste I leave in their mouth is the result of formatting or a difference in the selection of a particular algorithm.

    You’ll also notice (above) I use cell[x,y], not grid[x,y]. You’re only working with one grid, so how can you have multiple references? By saying cell[x,y], they know they are looking at the cell in position x,y. I could live with gridCell[x,y].

    If there are situations on projects which do not permit adequate planning (unfortunately, they exist all too often) and you’re forced into an XP situation (which I detest), I don’t write AddHitDataToCell, but Cell_HitData_Add. IOW, the verbs - OOP-style, appear at the end. If a class is called for, it becomes apparent rather quickly and the mindset is already there (as is the nomenclature for the class).

    If you follow behind someone in the ASP world, files named Customer_Add.asp, Customer_Delete.asp are going to be a heck of a lot more organized than if you say AddCustomer.asp, DeleteCustomer.asp, AddItemToInventory.asp, etc. If that’s not clear, when you bring up the directory of those files, you’ll see all of the “Add”s sorted together instead of “Customer_Add.asp”, “Customer_Edit.asp”, “Customer_Delete.asp”, “Customer_View.asp”. Looking back, I received a lot of email from people who did follow behind me on sites I developed who thanked me for this form of organization because it was intuitive. On top of that, those times when it was better, performance-wise, to move VBScript to VB, the class|object structure was already apparent in the filenames. Create the class, the methods, then copy|paste each file’s contents into the appropriate method’s location.

    In short: my style of coding becomes a case of lining up punctuation, making it pretty. My motto: if something doesn’t look right, it almost always isn’t right. I believe it should look as nice on the inside as it should behave for the user on the outside. It’s no different than the cross-stitch my wife puts together: the back is to be as nice as the front. And when you see the back of someone’s work which looks like a rat’s nest, you know you aren’t dealing with a craftsperson.

    I know my craft and I leave quality behind for those who must follow in my footsteps.

  79. mawi · 5 years ago

    One thing that I think you should add is a note on “magic numbers”:

    I believe that your example under “Inline commenting” is bad, because it uses magic numbers and “excuses” that usage by explaining the values in a comment. The preferred way is to use an constant, enum or other such device (they will of course be replaced by the value by the compiler anyway).

    I disagree with signing your work (Jonathan Aquino). I dont think it rhymes well with the XP principles; check your ego at the door and collective code ownership which we find are essential practices for effectiveness (albeit another popular discussion).

    Definitely skip the BUG or other comments. HACK / etc is disgraceful and TODO is unbearable, like Thomas Stigsen says. Commented code likewise. Commit good code only, trust your versioning system, test suite and integration server.

    I agree with the essence of Bob Smiths comment.

    Joshua Olson: Interesting, I think that is the way most think, intuitively TDD yet not formalized. I would write a test with real code like that first, then implement it.

    Agree with Doug on the isAlive comment.

  80. Denis Krukovsky · 5 years ago

    I published article on the same subject not so long ago. I used practical approach, meeting with problems which stop developer from writing comments, and proposing practical solutions. I recommended an opposite to ??write comments at the same time (or earlier than) you code?? and explained why. Welcome to http://dkrukovsky.blogspot.com/2005/07/how-to-write-comments.html

    Denis Krukovsky http://dotuseful.sourceforge.net/ http://dkrukovsky.blogspot.com/

  81. Phaderunner · 5 years ago

    “A common implementation of this is called Hungarian Notation.”

    No it isn’t, Hungarian Notation is the practice of putting characters representing the TYPE of variables at the front of their names. Meaningful variable and function names is called nothing except best practice!

    If you are going to get all evangelical about function commenting why not introduce things like Doxygen and Javadoc that pick up on standard forms of function comment. Use those forms instead and don’t go creating another new one.

    For god’s sake don’t build your own style, use one which is used within the community or company you are programming for and stick to it. Consistency is a good thing.

  82. spider57 · 5 years ago

    “No it isn’t, Hungarian Notation is the practice of putting characters representing the TYPE of variables at the front of their names. Meaningful variable and function names is called nothing except best practice!”

    G’day,

    Not quite. What you refer to is Systems Hungarian which misconstrued Charles Simonyi’s original intent.

    He intended to classify a variable’s name based on the type of the variable, e.g. unsafe, read-write, safe, etc. This is what is known as Apps Hungarian.

    Unfortunately, this was misconstrued as the type indentifier for the variable, this is the “lovely” Systems Hungarian.

    Joel S. has written an interesting “essay”:http://www.joelonsoftware.com/articles/Wrong.html that clarifies this distinction. There are links to CS’s original paper at the bottom of Joel’s essay. cheers, Rob

  83. spider57 · 5 years ago

    Sorry. That of course should read:

    Joel S. has written an interesting “essay”:http://www.joelonsoftware.com/articles/Wrong.html that clarifies this distinction.

    cheers, Rob

  84. Giorgos · 5 years ago

    Joshua Olson wrote:

    bq. I just wanted to share a technique that works for me. Maybe it’ll work for you too. When I build a function, it generally starts something like this:

    function ProcessRequest(Player p, Action a) { // Step 1. Validate request // Step 2. Create local variables // … }

    This is what I usually do too. Then, the comments either go away, or get expanded with more descriptive, detailed text if the respective part of the source seems to need it.

  85. Max Nokhrin · 5 years ago

    Nice article. I will agree with those who are against Hungarian Notation. I hate it. With a passion. My favourite so far is something along the lines of:

    Private Sub funCalculateTotal(ByVal Items as Cart) As Double

    Does it calculate a “fun” total? Anytime I have to work with code written in this way, I have to double-check what the hell the function or variable was called before using it. Extremely annoying.

  86. Shawn Starr · 5 years ago

    I generally follow the Open Source commenting structure. Where FIXME is used to indicate code that although works, isn’t pretty and should be redone properly.

    Ie:

    /* FIXME: This code could be optimized better. Blah blah blah….. */

  87. Charles Thayer · 5 years ago

    Thanks for the article. I think it’s important to comment intent as opposed to function. This falls in line with the notion of “reusable comments”. Function or implementation may change, and one should read the code to determine function, but intent changes less, and provides real insight.

  88. Pavan Podila · 5 years ago

    Many of the points discussed here have already been put together in Code Complete by Steve McConnell. It is definitely worth referring back once in a while. The 2nd edition includes more OO languages.

  89. Brett Walker · 5 years ago

    I agree, Steve McConnell’s book is a must read, but there are some new topics that may warrant further discussion.

    Well-commented code is a thing of beauty, and a thing of beauty is a joy forever.

    -Brett Walker, http://www.vertabrett.com

  90. Mark · 5 years ago

    Good write up. With a couple of my projects needing some attention, I’m hoping that the commenting I did before will help me and not hinder me this time around.

    Found you on del.icio.us/popular

  91. Curt Sampson · 5 years ago

    I’m trying to remember if it was Ron Jeffries or someone else in that crowd, but the first time he headed over to the CCC project and started reading code from Kent Beck’s group, he was amazed. There were no comments, but the code itself read like English. And that ensured that the “comments” could never be out of date or wrong.

    Write the code for humans to read and understand easily. Then write whatever you need to make that code execute.

  92. AkA · 5 years ago

    Everyone needs a hug.

  93. Paul McKay · 5 years ago

    Everyone needs a hug - collect yours soon!

    I totaly agree that commenting improves code for everyone. What I’d really like is an IDE environment (I’m currently using VS.NET) where you could put comments in a different font or in bold etc. etc. to flag their relative importance. (Not all comments are created equal.) Am I alone in this wish? Do you know if it’s already been done? I think it’s awful that Microsoft et al expect code to be in Courier. Aaargh!

  94. Lynn · 5 years ago

    Good article. I would just like to add one thing: “Just do it”

    Most of the code that I see doesn’t have ANY comments! Come on guys (girls) ! We’re supposed to be professionals here. What makes you think I want to waste MY time reading through your code !? What we really need is compilers that won’t work if there aren’t any comment blocks.

  95. Maverick · 5 years ago

    Fantastic article. Not only does it tells the do’s and dont’s but also inspires budding programmers to ensure that they do add comments whenever they code.

  96. Nathan Smith · 5 years ago

    Great article. I’ve recently started not only commenting my CSS a little more clearly, but also sat down one day and alphabetized everything, per a suggestion by “Chris J. Davis”:http://www.chrisjdavis.org/. It’s made it so much easier finding my way around, not to mention making it easier to decide where to put things as I’m writing new CSS attributes.

  97. Chris Campbell · 5 years ago

    I am a firm believer in commenting and I have delevoped macros for my editor to ease the commenting work load.

    Comments should answer 3 questions: 1) Purporse - What is this supposed to do? 2) Method - How are you doing it (don’t just repeat the code, explain)? 3) Reason - Why did you choose this method?

    The last question may be the least answered and most useful to have when you have to work with existing code. A simple statement like “I used the insertion sort because it was easy to code and we are dealing with a small number of elements” or “I had to use the insertion sort here because there is a bug in version X.Y of compiler ABC when using the quick sort method” says volumes to the next person to touch the code.

  98. Ketan Suri · 5 years ago

    Excellent Article: What I do for my code is whenever I start with a function I write the whole understanding of what it will do after it has been coded. Also if there are conditions, I draw a table and do a binary logic in the table saying if condition A is true and B is fals or A exist and B does not what will the code do. By just glancing at the table, other programmer get what the code is all about and it helps in testing too :o)

  99. laura herald · 5 years ago

    I find adding lots of whitespace reveals logic more to me than inline commenting.

    pseudo code commenting at the beginning of code without design documents usually stands the test of time and with a little tweaking serves a good purpose

    like the previous poster commented - comment what the app does and not how

  100. Wesley Walser · 5 years ago

    As one of the best things that you can do for yourself, and others that may at some point work with your code, articles like this stand to move everyone in a forward direction.

  101. Pierre Cloutier · 5 years ago

    Good: tabs. Bad: spaces.

    You’re telling me that hitting the ‘Space’ key sixteen times is better than four tabs? Nuts!

    Most editors allow you to define the column value of a tab, to your taste.

    Also, putting bug numbers is important because it can cross-reference to documents, screen shots and information not available in the source.

    Finally:

    Good: if(condition) { expression… }

    Illegible: if(condition) { expression… }

    There you go.

    I’ve only been coding since 1965. (CDC 3100 FORTRAN)

  102. Ryan Campbell · 5 years ago

    Pierre - I agree with your first two points. As far as the third goes, I used to do this:

    if(condition) { expression… }

    I was very stubborn about it too. One day I tried the other version, and it made things much easier for me to visualize. Do you like the version you flagged as “Good” because of personal preference, or has that been a standard in most programming enivronments you have been a part of?

    I’m truly curious. I’ll break a bad habit now if I agree with your logic.

  103. Joachim S · 5 years ago

    Aloha!

    Great article. I’ve been writing SW code and HW description code (Verilog and VHDL) for years and I have adopted a style that I try to use on all my source files (with variations based on language rules).

    Basically they boils down to:

    (1) File header AND footer. The footer is basically and EOF . But I find that it helps greatly, esp when looking at printouts. Header and footer are framed with a row of “=” 72 characters in length.

    The header names the file, describes the contents and the purpose of the contents (for example interface module for the design of ASIC XYZ, database class used in the processor model QWERTY etc) any special design considerations, references to design specifications that might be of interest etc. Finally the header ends with author name, copyright and that PHB-stuff. (Yes, I do sign all my work.)

    (2) Framed comments preceeds functions/processes. comments. That is, all functions/processes are preceeded by a comment that describes the intended functionality, pre- and post-conditions, specific code details etc. These comments are framed with a row of “-” 68 chars in length.

    (3) Whitespaces. I use blank lines to separate chunks of code within a function, between functions. I use the cosistently with, for example, always two (2) lines between functions.

    (3) Comments within functions preceeds a chunk of code. The comments explains the purpose and any specific detail - reasons for doing a certain thing. (If needed.)

    (4) Use different comment types for comments and code debug. In C/C++ I use “//” for all code comments. This allows med to use “/* .. */” to comment out blocks of code. Also I can easily spot is a comment is for documentation or not. Languages that don’t support (at least) two types of comments are quite annoying to work with.

    (5) Code sections are named and divided. I try to layout the contents of the code in a file in a common way. Normally something like:

    (I) Includes and defines (II) Module interface (if any) (III) Any global variables (common in HW) (IV) Storage element allocation and handling (V) Data flow/manipulation code (fun/process) (VI) Control flow code

    These sections are are declared and framed off using a one line section declaration framed with upper- and lowe rows of “-” 72 chars long.

    Note that I use 72 chars for headers and sections, and 68 chars for function headers. This allows me to visually see where section ends.

    A brief note on {} (or BEGIN-END). They IMHO should be alligned together. For example

    void kalle() { do_something(); }

    And when it comes to intendation. Any good editor (i.e. Emacs) allows you to set that it actually produces n number of space characters when you press TAB. Intendation shall be done using space, but you should not need to actually hit that bar that many times - it opens up for errors.

    /Joachim S - ASIC designer at large

  104. Jeff · 5 years ago

    Bravo. Too many programmers spend little time and apply little thought in making their comments meaningful. I think you made very important points in terms of style, consistency and readability.

    I don’t actually code, but often a programer or their manager will print out a section of code for troubleshooting/review. Having the code properly commented - in a manner similar to what you describe - greatly increases our efficiency as we can become familiar with the logic quickly and leverage the problem solving abilities of some of our non-programmers. Utilizing proper commenting is the only way that we can effectively do this across platforms and languages. Good read. I’m going to forward to my staff as a helpful link.

  105. Ken · 5 years ago

    I agree with promoting code commenting as a general practice by programmers. But I also want to echo what Tom said about outdated comments. If there is one thing worse than comment-less code, it is incorrectly commented code. I’ve made the mistake of trusting comments that were no longer true, and paid for it with hours of searching through the code.

    I think comments should be added judiciously so that whoever changes that code in the future would be more likely to update the comments as well.

  106. Davee · 5 years ago

    Well-written article even though my personal preferences differ from yours.

    As a long-time coder (and occasional PHB :-)), it’s my experience that any non-trivial code needs commenting. Non-trivial in this sense is any code used for more than a couple of months by more than a couple of people or code that ever serves more than its original narrow purpose.

    I worked as a Big-5 consultant for a number of years on a project for a large US state gov’t agency. In that time, the code had (I counted!) 47 sets of hands in it. Commenting was critical to help us understand a) what the various modules were supposed to do or how they were intended to do it, b) how badly the writer had misinterpreted the voluminous and detailed specs and c) making decisions about refactoring interfaces for a move from client-server to web-based (the comments helped indicate dependencies).

    My current position is the 6th or 7th developer on a commercial product that’s been around in one form or another for 10+years. Comments are important to me here b/c I was not around for the design or implementation decisions for the framework I’m maintaining/extending.

    To those who say ‘well-writen code needs no comments’ I say ‘read your own crap after a couple of years or a dozen other projects’. Unless you are lucky enough to be able to walk away from all not-new-development work, sooner or later you will have to either pick up someone else’s leavings or you’ll have a client that wants your months- or years-old code modified. At that point, having to read code to see what’s going on will be an expensive indulgence, either in billable hours or time with the family or whatever your value proposition is.

  107. Bill · 5 years ago

    All you Hungarian haters really should read the article pointed out by pooly http://www.joelonsoftware.com/articles/Wrong.html

    and the article pointed out by Alex (history of hungarian notation) http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnvs600/html/HungaNotat.asp

    when used as intended it can be very useful. When used to show that an int is an int - well, its a waste of time.

  108. Pete · 5 years ago

    Your example code looks like javascript. Javascript code for a production system should of course be commented but stripped out before putting it in the production environment. Forcing your users to download your comments over and over again creates bad performance.

  109. Eric Wang · 5 years ago

    I just wanted to share a technique that works for me. Maybe it’ll work for you too. When I build a function, it generally starts something like this:

    function ProcessRequest(Player p, Action a) { // Step 1. Validate request // Step 2. Create local variables // Step 3. Collect object rules for evaluation // Step 4. Perform action on Player object ……. Posted by Joshua Olson · 28 days ago · Link It’s my favorite method when I create functions, BUT, there is a drawback in this method, sometimes when you maintain the fucntion, you must change the inside logic, the step sequence will be crashed, for example, the step3 is removed, then you should modifiy the comments to maintain the readability. Maybe you should go through all the function just to change the step index in the comment, you will hate yourself for the over comment:)

  110. Roel · 5 years ago

    I prefer to go that extra mile and write nearly all of my comments under form of unit tests. That way I know that they are valid. If not they tend to quickly become outdated :-(

    But for the occasional case where I want to put some comment in my code, these tips will be very helpfull indeed.

  111. google · 5 years ago

    Interesting, good job

  112. links@vp-shops.com · 5 years ago

    Vietnam shopping collections: handmade wood, art culture, handicraft, craft, embroidery, embroidery…