[Year 12 SofDev] Query about Internal Documentation

Bucknell, Chris cbucknell at whitefriars.vic.edu.au
Fri May 4 10:18:05 EST 2012


I came across a M$ document a while ago Called "All-In-One Code Framework Coding Standards" which is for all .Net languages.  I use an edited version (below) of this for my class when coding in VB to describe how to comment and layout their code.

Hope this is of use

Regards Chris



Pro-Comment Point #1: It's important to communicate what the code SHOULD be doing

Source code must follow the syntactic tenants of the computer language. While language designers make significant efforts to define a readable syntax, at its core the language syntax exists for the compiler or interpreter and not the developer. Thus, comments are required to communicate the intent of the source apart from its functionality. When reading source code, it is extremely difficult to be absolutely certain of what the code is doing, as well to be certain as to what the original author intended. Comments should clearly communicate the developer's intent and if needed, an explanation as to how the source code algorithm accomplishes that intent.

Pro-Comment Point #2: Comments show respect for the next developer to read your code

The Golden Rule applies in source code as well; do unto the next developer as you would have them do unto you. Source code should be written in the way that you yourself would most like to encounter unfamiliar code. It should be well-structured with a clear logic flow, and be both efficient and effective. Comments enhance the readability of the code, so that its intent and approach are immediately apparent with a clean appearance.

Pro-Comment Point #3: Comments indicate potential problem areas to avoid

Comments should mention factors that may be of concern for the developer or tester. Boundary conditions, valid argument ranges, and corner cases are all important factors to mention in comments for the benefit of future developers and testers.



1. Whitespace

1.1 Blank Lines

* You should use blank lines to separate groups of related statements.  Omit extra blank lines that do not make the code easier to read.  For example, you can have a blank line between variable declarations and code.



Good:

Sub ProcessItem(ByVal item As String)

    Dim counter As Integer = 0

    Dim flag As Boolean = True



    If flag Then

        'Do something

    End If

End Sub



Bad:

Sub ProcessItem(ByVal item As String)

    Dim counter As Integer = 0

    Dim flag As Boolean = True







    If flag Then

        'Do something

    End If







End Sub



In this example of bad usage of blank lines, there are multiple blank lines between the local variable declarations, and multiple blank likes after the 'if' block.



* You should use two blank lines to separate method implementations and class declarations.



1.2 Spaces

Spaces improve readability by decreasing code density. Here are some guidelines for the use of space characters within code:

* You should use spaces within a line as follows.



Good:

CreateFoo()                ' No space between function name and parenthesis

Method(myChar, 0, 1)       ' Single space after a comma

x = array(index)           ' No spaces inside brackets

While (x = y)              ' Single space before flow control statements

If (x = y) Then            ' Single space separates operators



Bad:

CreateFoo ()               ' Space between function name and parenthesis

Method(myChar,0,1)         ' No spaces after commas

CreateFoo( myChar, 0, 1 )  ' Space before first arg, after last arg

x = array( index )         ' Spaces inside brackets

While(x = y)               ' No space before flow control statements

If (x=y) Then              ' No space separates operators



2. Comments

* You should use comments that summarize what a piece of code is designed to do and why. Do not use comments to repeat the code.



Good:

' Determine whether system is running Windows Vista or later operating

' systems (major version >= 6) because they support linked tokens, but

' previous versions (major version < 6) do not.



Bad:

' The following code sets the variable i to the starting value of the

' array.  Then it loops through each item in the array.



* You should use single-line syntax (' ...) is preferred even when a comment spans multiple lines.



Good:

' Get and display the process elevation information (IsProcessElevated)

' and integrity level (GetProcessIntegrityLevel). The information is not

' available on operating systems prior to Windows Vista.

If (Environment.OSVersion.Version.Major >= 6) Then

End If



* You should indent comments at the same level as the code they describe.



* You should use full sentences with initial caps, a terminating period and proper punctuation and spelling in comments.



Good:

'Initialize the components on the Windows Form.

InitializeComponent()



Bad:

'initialize the components on the Windows Form

InitializeComponent()



2.1 Inline Code Comments

Inline comments should be included on their own line and should be indented at the same level as the code they are commenting on, with a blank line before, but none after. Comments describing a block of code should appear on a line by themselves, indented as the code they describe, with one blank line before it and one blank line after it.  For example:



If MAXVAL >= exampleLength Then
    ' Reprort the error.
    ReportError(GetLastError())

    ' The value is out of range, we cannot continue.
    Return E_INVALIDARG
End If

Inline comments are permissible on the same line as the actual code only when giving a brief description of a structure member, class member variable, parameter, or a short statement.   In this case it is a good idea to align the comments for all variables.  For example:



    Dim MAX_STUDENTS As Integer = 20 'The maximum number of students allowed



    Do

        ...

    Loop While Not finished 'Continue if not finished



* You should not drown your code in comments. Commenting every line with obvious descriptions of what the code does actually hinders readability and comprehension. Single-line comments should be used when the code is doing something that might not be immediately obvious.



The following example contains many unnecessary comments:



Bad:

'Loop through each item in the student array

For i As Integer = 1 To MAX_STUDENTS

    Dim stud As String = students(i) 'Get the next student

    If Left(stud, 1) = "a" And stud.Length > longestName Then 'Process if it's a name starting with "a" and its the longest

        longestName = stud.Length 'Save the length as the longest

        biggestName = stud 'Remember the student as well

    End If

Next



Good:

' Loop through each item in the student array, find the student with

' the longest "A" name, and store it in 'biggestName'.

For i As Integer = 1 To MAX_STUDENTS

    Dim stud As String = students(i)

    If Left(stud, 1) = "a" And stud.Length > longestName Then

        longestName = stud.Length

        biggestName = stud

    End If

Next



* You should add comments to call out non-intuitive or behavior that is not obvious from reading the code.





2.2 File Header Comments

* Do have a file header comment at the start of every human-created code file. The header comment templates are as follows:



VB.NET file header comment template:



'***************************** Module Header *******************************

' Module Name:  <File Name>

' Project:      <Sample Name>

' Copyright (c) Microsoft Corporation.

'

' <Description of the file>

'

' This source is subject to the Microsoft Public License.

' See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.

' All other rights reserved.

'

' THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,

' EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED

' WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.

'***************************************************************************



For example,



'****************************** Module Header ******************************

'Module Name:  CppUACSelfElevation.cpp

'Project:      CppUACSelfElevation

'Copyright (c) Microsoft Corporation.

'

'User Account Control (UAC) is a new security component in Windows Vista and

'newer operating systems. With UAC fully enabled, interactive administrators

'normally run with least user privileges. This example demonstrates how to

'check the privilege level of the current process, and how to self-elevate

'the process by giving explicit consent with the Consent UI.

'

'This source is subject to the Microsoft Public License.

'See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.

'All other rights reserved.

'

'THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,

'EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED

'WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.

'***************************************************************************



2.3 Class Comments



* You should provide banner comments for all classes and structures that are non-trivial. The level of commenting should be appropriate based on the audience of the code.



VB.NET class comment template:



''' <summary>

''' <Class description>

''' </summary>





2.4 Function Comments



* You should provide banner comments for all public and non-public functions that are not trivial. The level of commenting should be appropriate based on the audience of the code.



VB.NET function comment template:



''' <summary>

''' <Function description>

''' </summary>

''' <param name="Parameter name">

''' <Parameter description>

''' </param>

''' <returns>

''' <Description of function return value>

''' </returns>

''' <exception cref="<Exception type>">

''' <Exception that may be thrown by the function>

''' </exception>



For example,



''' <summary>

''' The function checks whether the primary access token of the process

''' belongs to user account that is a member of the local Administrators

''' group, even if it currently is not elevated.

''' </summary>

''' <param name="token">The handle to an access token</param>

''' <returns>

''' Returns true if the primary access token of the process belongs to

''' user account that is a member of the local Administrators group.

''' Returns false if the token does not.

''' </returns>

''' <exception cref="System.ComponentModel.Win32Exception">

''' When any native Windows API call fails, the function throws a

''' Win32Exception with the last error code.

''' </exception>



Any method or function which can fail with side-effects should have those side-effects clearly communicated in the function comment. As a general rule, code should be written so that it has no side-effects in error or failure cases; the presence of such side-effects should have some clear justification when the code is written. (Such justification is not necessary for routines which zero-out or otherwise overwrite some output-only parameter.)



2.5 TODO Comments



* Do not use TODO comments in any released samples. Every sample must be complete and not require a list of unfinished tasks sprinkled throughout the code.




From: sofdev-bounces at edulists.com.au [mailto:sofdev-bounces at edulists.com.au] On Behalf Of Ben Hines
Sent: Friday, 4 May 2012 9:34 AM
To: sofdev at edulists.com.au
Subject: [Year 12 SofDev] Query about Internal Documentation

Hey List!

Just wondering what the standards/conventions are for internal documentation (Comments). Are there any or do we just teach our students to sensibly comment sections of code with a little explanation of what the code is achieving. The main thing I learnt at uni was when commenting don't go too overboard with explanations...

Any ideas?

Mr Ben Hines

VCE Maths/ICT Teacher
Senior School Campus - Christian College Geelong
*(03) 52411577 (ext. 180)


This e-mail is intended for the use of the named individual or entity and may contain confidential and privileged information. Any dissemination, distribution or copying by anyone other than the intended recipient of this e-mail is strictly prohibited. If this e-mail has been received in error, then please notify Christian College or the author of this email immediately and destroy the original message. We have made every attempt to ensure this e-mail message is free from computer viruses however the attached files are provided on the basis that the user assumes all responsibility for use of the material transmitted. Views, opinions, etc. expressed reflect those of the author and not Christian College nor its associated companies and campuses which includes Eden Quality Services Pty Ltd.
________________________________
Message protected by MailGuard: e-mail anti-virus, anti-spam and content filtering.
http://www.mailguard.com.au


-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.edulists.com.au/pipermail/sofdev/attachments/20120504/7c83994e/attachment-0001.html 


More information about the sofdev mailing list