Rules to Better Code Commenting

​Rules for adding comments to code.​

Hold on a second! How would you like to view this content?
Just the title! A brief blurb! Gimme everything!
  1. Comments - Do you know what to do with comments and Debug.Print statements

    ​​​When you create comments in your code, it is better to document why you've done something a certain way than to document how you did it. The code itself should tell the reader what is happening, there's no need to create "how" comments that merely restate the obvious unless you're using some technique that won't be apparent to most readers.

    ​What do you do with your print statements? Sometimes a programmer will place print statements at critical points in the program to print out debug statements for either bug hunting or testing. After the testing is successful, often the print statements are removed from the code. This is a bad thing to do.

    Debugging print statements are paths that show where the programmer has been. They should be commented out, but the statements should be left in the code in the form of comments. Thus, if the code breaks down later, the programmers (who might not remember or even know the program to start with), will be able to see where testing has been done and where the fault is likely to be - i.e., elsewhere.

    private void Command0_Click() {
        rst.Open("SELECT * FROM Emp") // Open recordset with employee records​
        // Debug.Print("Got " + intCount + " results");
        if (intCount > 1000) {
             // Debug.Print("too many records - returning early");
            return;
        } else  {
        .....processing code
    }

    Bad Example​ - Debug code has just been commented out

    private void Command0_Click() {
        rst.Open("SELECT * FROM Emp")
    ​    // Count will exceed 1,000 during eighteenth century
        // leap years, which we aren't prepared to handle.
        if (intCount > 1000) {
            return
        } else  {
        .....processing code
    }

    Good Example - the debug commands have been rafactored into meaningful comments for the next developer
  2. Do you know the best way to track comments when your code is updated?

    ​​​​​​​​It's important that you have consistent commenting for your code, which can be used by other developers to quickly determine the workings of the application. The comments should always represent the rationale of the current behaviour.

    Since applications evolve over time - don't add comments to your code with datetime stamps. If a developer needs to see why the code behaves the way it does right now - your commit history is the best place to tell the story of why the code has evolved.​​​ 

    Commands such as git blame or Visual Studio's annotate are great ways of seeing who and when a line of code was changed. 

    private void iStopwatchOptionsForm_Resizing(object sender, System.EventArgs e) {
        // Don't close this form except closing this application - using hide instead; 
        if (!this.m_isForceClose) {
            // <added by FW, 11/10/2006>
            // Remind saving the changes if the options were modified.
            if (this.IsOptionsModified) {
                if (MessageBox.Show("Do
    you want to save the changes?", Me.GetApplicationTitle, MessageBoxButtons.YesNo,
    MessageBoxIcon.Warning) = DialogResult.Yes) {
                    this.SaveOptions()
                }
            }
            // </added>
        }
    }

    Figure: Bad example - timestamped comments add noise to the code

    comment annotations.png

    Figure: Good example - we can tell who added the comment using annotations
  3. Comments - Do you create Task List Comments for your code?

    ​​Task List comments can be used to indicate a variety of work to be done at the location marked, including:

    • features to be added;
    • problems to be corrected;
    • classes to implement;
    • place markers for error-handling code;
    • reminders to check-in the file.

    As with other Task List entries, you can double-click any comment entry to display the file indicated in the Code Editor and jump to the line of code marked. More details for Task List comments.

    pic1.png

    ​​Figure: Bad example - the comment doesn't show in Task List window

    pic2.png 

    Figure: Good example - Marked TODO in the comment, so you can see it in Task List window and double-click to jump to


    pic3.png

    Figure: Good example - Marked HACK in the comment, so you can see it in Task List window and double-click to jump to


  4. Comments - Do you follow the general commenting rules?

    ​​There is almost always a better alternative to adding comments to your code.
    What are the downsides of comments? What are the alternatives? What are bad and good types of comments? 


    There is almost always a better alternative to adding comments to your code. [Chapter 4: Comments, Clean Code is a treatise par excellence on the topic.]

    What are the downsides of comments?

    1. Comments don't participate in refactoring and therefore get out of date surprisingly quickly.
    2. Comments are dismissed by the compiler (except in weird languages like java) and therefore don't participate in the design.
    3. Unless strategically added, they place a burden on the reader of the code (they now have to understand 2 things: the code and your comments).

    What are the alternatives to comments?

    1. Change name of the element (class, function, parameter, variable, test etc.) to a longer more apt name to further document it.
    2. For ‘cryptic’ code (perhaps to optimize it), rewrite it in simpler terms (leave optimization to the runtimes).
    3. Add targeted unit tests to document a piece of code.
    4. Innovative techniques that are well known solutions to common code smells e.g.:
      1. For large methods/classes, break them and have longer names for them.
      2. For a method with large number of parameters, wrap them all up in a Parameter Object.
      3. <pair up with someone else, think… be creative.>

    What some *bad* types of comments?
    1. That explain the "what"/"how" of the code. Basically the code rewritten in your mother tongue.
    2. Documentation comments in non-public surface area.
    3. Commenting out the code itself (perhaps to work on it later? That’s what source control is for).
    4. TODO comments (Little ones are OK, don't leave them there for too long. The big effort TODOs - say that are over an hour or two - should have a work item URL to it).
    5. And many more…

    What some *good* types of comments?
    Very few of these really. Although even these are subject to all the downsides of comments.
    Note that a lot of punch can be delivered in 140 characters! Twitter previously?
    1. Comments that explain the why (e.g. strategic insights).
    2. … that hyperlink to an external source where you got the idea/piece of code.
    3. … that hyperlink to a Bug/PBI for adding some context.
    4. … that are documentation comments for your next-biggest-thing-on-Nuget library.
    5. … that are real apologies (perhaps you had to add some gut-wrenching nasty code just to meeting time constraints, must be accompanied by a link to Bug/PBI).


    Last but not the least, some parting words from @UncleBob himself:​
    "A comment is an apology for not choosing a more clear name, or a more reasonable set of parameters, or for the failure to use explanatory variables and explanatory functions. Apologies for making the code unmaintainable, apologies for not using well-known algorithms, apologies for writing 'clever' code, apologies for not having a good version control system, apologies for not having finished the job of writing the code, or for leaving vulnerabilities or flaws in the code, apologies for hand-optimizing C code in ugly ways."
    - Uncle Bob (Robert Martin of 'Clean Code' fame)


  5. Comments - Do you add a comment when you use Thread.Sleep?

    ​​​First don’t do it and find the right fix. But if you have to, it should always be commented – as though your life depended on it.​ 

    public DialogResult RefreshSchema() {
        SSW.SQLAuditor.WindowsUI.QueryAnalysisForm.RunScript(Startup.PageQueryAnalyzer.txtScript.Text)
        System.Windows.Forms.Application.DoEvents()
        // This is a sleep to delay the Application.DoEvent process.​
        System.Threading.Thread.Sleep(500)
        System.Windows.Forms.Application.DoEvents()
        ...
    }​

  6. Do you know what to do with a work around?

    If you have to use a workaround you should always comment your code and reference. You should also make a Suggestion to [Product] if you think it is something that the product should do.

    1. Comment in the code with URL to an existing or new Suggestion
    2. Create a Suggestion to .NET 3 that points to blog post


    "This is a workaround as per the suggestion 
    "[URL]

    Figure: Always add a URL to the suggestion that you are compensating for

    ​Exercise: Understand commenting

    You have just added a grid that auto updates, but you need to disable all the timers when you click the edit button. You have found an article on Code Project (http://www.codeproject.com/Articles/39194/Disable-a-timer-at-every-level-of-your-ASP-NET-con.aspx) and you have added the work around.

    Now what do you do?

    Sub OnPagePreRender(ByVal sender As Object, ByVal e As EventArgs)
    ' Fix for pages that allow edit in grids
    Me.FindControls(Of System.Web.UI.Timer).ForEach(Sub (c) c.Enabled = False)
    End Sub

    Figure: Work around code in the Page Render