1. Comments help explain code logic and document changes over time.
2. Comments should be written at a consistent and readable style for each code component.
3. Comments are most useful when added while writing code to capture intent and context.
2. 1. Process Documentation
2. Code Commenting
Code Commenting – First thing we learnt incorrectly as a Programmer
“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.”
What Microsoft Says:
1. The purpose of adding comments to code is to provide an understandable description of what your
code is doing.
2. Comments should provide information that is not otherwise available from reading the code itself.
3. Good comments are written at a higher level of abstraction than the code itself.
4. Comments that only restate what is already obvious add nothing to the code and should be avoided.
What I think:
• First and foremost, comments help you, the programmer, remember what you've done. This is
especially important when debugging your code.
• Well-placed comments can be very helpful in determining whether the code actually does what you
think it does.
• Comments that provide an “outline” of the algorithm can remind you what is happening at each stage
of the program and also show us, the instructors, that you do know what's going on, even if it doesn't
work correctly.
3. • Comments will also be useful when others are trying to determine what your code does. Specifically, if you
come to office hours with a question, comments can help us help you better. Also, if anyone (including you)
sees your code at a much later date, the comments will provide insight into design decisions that you may not
remember or that you may not be available to explain.
In addition, if your comments speak to how the code works, instead of to what it does, you have created
an additional code-maintenance problem, because comments that describe how code works must be
revised whenever you change the code. Failing to maintain these comments along with the code creates a
risk that the comments will no longer describe the code.
Summary:
1. Makes your understanding better.
2. Helps you as well as others in future and saves time.
3. Your logic becomes clearer when you comment along with code.
4. They should not state what code does.
Okay, so we agree that commenting code is a Good and Useful Practice. Now, why must we have a standard? In
terms of this course, a standard gives us a way to evaluate your comments as part of the grading for each lab.
Also, we know that standards are used extensively in industry, and we want you to gain experience working
within prescribed parameters. In practice, you will likely be required to follow much more stringent coding
standards than those given in this course.
4. Types of Comments
1. Code Commenting
2. Inline Commenting
3. Function Commenting
4. Class / Page Commenting
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(string userName, int userAge)
Without any additional information, you can tell that the function will add a user’s name and age to a database
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 AddUserToDatabase(string userName, string userAge)
{
if(userAge > 20) // Under 20 users will go into Primary level
SaveUser(userName, userAge)
}
5. 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 : This function is used to save all secondary level
users into existing database.
Parameters: It takes 2 parameters. First one as user name
and other one for user age.
Return: It returns true or false after the completion of
process.
Author: Deepak Tripathi – 10-Dec-2011
Modifier: 1. Rohit On 11-Dec-2011(Changed User Age
Condition from 20 to 25)
2. Ajay On 1-Jan-2012 (Changed User Age
Condition from 25 to 20)
*/
function bool AddUserToDatabase(string userName, string userAge)
{
if(userAge > 20) // Under 20 users will go into Primary level
SaveUser(userName, userAge)
}
6. 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.
/*
Summary : This function is used to save all secondary level
users into existing database.
Author: Deepak Tripathi – 10-Dec-2011
Modifier: 1. Rohit On 11-Dec-2011(Changed function
AddUserToDatabas)
2. Ajay On 1-Jan-2012 (Changed function
AddUserToDatabas)
*/
Namespace CarWale.CRM
{
Public Class AddUsers : Page
{
protected string from , to;
void Page_Load(object Sender, EventArgs e)
{
AddUserToDatabase(“Deepak”, 27)
}//Page Load
function bool AddUserToDatabase(string userName, string userAge)
{
if(userAge > 20)// Under 20 users will go into Primary level
SaveUser(userName, userAge)
} //AddUserToDatabase
}//Class
}//NameSpace
7. Do’s and Don'ts:
Do’s:
1. Focus on readability of code
assume that you don't have comments to explain the code. Give your method, variables and class
meaningful name.
2. Precede comments by a blank line: Doing this creates a distinct separation between your code and
comments. Plus, it’s visually pleasing. 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:
int maxUsers = 2 //all players
int maxPoints = 100000 //needed to win game
3. Comment each level with a consistent style
Comment each code block, using a uniform approach for each level. For example:
• For each class, include a brief description, author and date of last modification
• For each method, include a description of its purpose, functions, parameters and results
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.
4. Use paragraph comments
Break code blocks into multiple “paragraphs” that each perform a single task, then add a comment at the
beginning of each block to instruct the reader on what is about to happen.
8. // Check that all data records are correct
foreach (Record record in records)
{
if (rec.checkStatus()==Status.OK)
{
...
}
}
// Now we begin to perform transactions
Context ctx = new ApplicationContext();
ctx.BeginTransaction();
...
5. Be polite
Avoid rude comments like, “Notice the stupid user has entered a negative number,” or “This fixes the side
effect produced by the pathetically inept implementation of the initial developer.” Such comments do not
reflect well upon their author, and you never know who may read these comments in the future: your
boss, a customer, or the pathetically inept developer you just insulted.
6. Use special tags for internal use
When working on code as a team, adopt a consistent set of tags to communicate among programmers. For
example, many teams use a “TODO:” tag to indicate a section of code that requires additional work:
int Estimate(int x, int y)
{
// TODO: implement the calculations
return 0;
}
9. Tag comments don’t explain code; rather they seek attention or deliver a message. But if you use this
technique, remember to follow up and actually do what the message is asking.
7. Comment code while writing it
Add comments while you write code and it’s fresh in your memory. If you leave comments until the end, it
will take you twice as long, if you do it at all. “I have no time to comment,” “I’m in a hurry,” and “The project
is delayed” are all simply excuses to avoid documenting your code. Some developers believe you should
write comments before code as a way to plan out your ultimate solution. For example:
public void ProcessOrder()
{
// Make sure the products are available
// Check that the customer is valid
// Send the order to the store
// Generate bill
}
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.
8. Write comments as if they were for you (in fact, they are)
When it comes to commenting code, think not only about the developers who will maintain your code in the
future, but also think about yourself.
“As soon as a line of code is laid on the screen, you’re in maintenance mode on that piece of code.”
As a result, we ourselves will be the first beneficiaries (or victims) of our good (or bad) comments.
10. 9. Update comments when you update the code
There is no point in commenting correctly on code if the comments are not changed with the code. Both
code and comments must move in parallel, otherwise the comments will actually make life more difficult for
developers who maintain your code. Pay special attention to refactoring tools that automatically update
code but leave comments unchanged and hence obsolete in the same instant.
10. The golden rule of comments: readable code
One of the basic principles for many developers: Let your code speak for itself. Although one suspects this
movement is led by programmers who do not like to write comments, it is true that self-explanatory code
can go a long way toward making code that’s easier to understand and can even render comments
unnecessary. For example, the code in my Fluid Interfaces article shows how clear self-explanatory code can
be:
Calculator calc = new Calculator();
calc.Set(0);
calc.Add(10);
calc.Multiply(2);
calc.Subtract(4);
Console.WriteLine( "Result: {0}", calc.Get() );
In this example, comments are not needed. To facilitate readable code, you might consider using proper
names,ensure correct indentation, and adopt coding style guides. Failure to comply with this tip may result
in comments that seem to apologize for bad code.
11. 11. Always try to finish your comment in as few words as possible, one liner comment is best until its
explaining "Why" part and can't be replaced by code itself. No body likes or has enough time to read longer
comment.
Closing brackets :
1 } // ... if see evil
2 } // ... while monkey do.
3 } // ... if monkey see.
4 } // ... class monkey
5} // ... namespace primate
Last but not the least give your code to fellow developer to understand as part of code review and ask him
how much he understands it.
Don’ts:
1. Don't write what code is doing: this should be left for the code to explain and can be easily done by giving
class, variable and method meaningful name. For example:
12. //calculates square root of given number
//using Newton-Raphson method
public void abc(int a)
{
r = a / 2;
while ( abs( r - (a/r)) > t )
{
r = 0.5 * ( r + (a/r) );
}
System.out.println( "r = " + r );
}
Above code is calculating squate root using Newton-Raphson method and instead of writing comment you
can just rename your method and variable as follows:
public void squareRoot(int num)
{
root = num/ 2;
while ( abs(root - (num/ root) ) > t )
{
r = 0.5 * (root + (num/ root));
}
System.out.println( " root = " + root );
}
13. 2. Don't write story in comment as your name, employee id, your department etc because those
information can be obtained from cvs commit data in case someone wants to know who has make this
change.
3. 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.
4. Don’t insult the reader’s intelligence
Avoid obvious comments such as:
if (a == 5) // if a equals 5
counter = 0; // set the counter to zero
This wastes your time writing needless comments and distracts the reader with details that can be easily
deduced from the code.