Home About

November 15th, 2008

Code commenting techniques in C# - 0

When writing new code everything seems so obvious that there is hardly a need to code any comments. But then you get that highly tuned and several times rewritten code library the company has been using for 20+ years. Attached to it is a note asking you to recode it in C# before the weekend.

If you have ever had to work with code left over by other programmers that are no longer around you appreciate the little comments they made on each of their coding decisions. Even your own code, dusted off after some years, can be intimidatingly hard to understand.

Just like C (and C++) C# offers two ways to comment your code: the /* this is a comment */ multi line comment, and the // single line comment.


/* Multi Line Comment Example
   Programmer: Martijn Dijksterhuis
   Date:       November 1, 2008
   Version:    1.0
*/

using System;    // standard IO library
using Gtk;       // We are writing code for Gnome

More important than proper commenting is the need for the code to be self explanatory. Smart and consistent use of variable and function names saves time figuring out what each part does, and reduces opportunity for bugs to creep into your code.

Compare the following two C# implementations of a simple standard mortgage payment calculator:

/* First Implementation */
double P     = 1000.25; 	   // Principal
double Yi    = 0.075;          // Yearly interest
double Y     = 12;             // Years
double mI    = Yi / 12;        // Monthly Interest

// Calculate the monthly payments
double p     = P * mI / (1 - (Math.Pow(1 / (1 + mI), Y * 12)));

/* Second Implementation */
double Principal       = 1000.75;
double YearlyInterest  = 0.075;
double Years           = 12;
double MonthlyInterest = YearlyInterest / 12;
double MonthyPayment   = Principal * MonthlyInterest / ( 1 - Math.Pow(1/(1+MonthlyInterest),Years*12)));

The first implementation requires much documentation in the form of comments to be readable. The second one is self documenting.

Image credit: dalvenjah

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google
  • Reddit

Tags: ,

Leave a Reply


Recent Comments
  • Hakbor: This works fine. But to get the NUnit to use my current tests (and not the old ones) , it is not sufficient...
  • Alberto: Your plugin is very useful; I installed it on several different blogs I manage and I’m very happy with...
  • Nelson: Saved me from doing it myself. Good article.
  • andy: i am currently playing taiwanese server wow in 奈辛瓦里(PVP) and i would like to realm transfer to...
  • berties: any english speaking playing on a taiwanese server?