During the years I’ve seen a lot of different ways of commenting code – some good and some bad. My personal favourite way of commenting code is by using the XML comment feature of C# and VB.NET, but the important part of commenting code is not how you do it, but what you write in them.
Methods are the most challenging members to comment, because they perform an action and can contain many lines of code compared to e.g. properties. Because of their relative complexity they need to be well commented, so lets take a look at what that actually means.
Answer the questions
The XML comments of a method needs to answer three simple questions: What, why and how. The simplest is “what”. In a class called Dog there is a public method called Bark() and the comment that answers the "what"-question could be Makes the dog bark out loud.
Next we want to answer the "why"-question and it is a bit trickier. The answer must tell you why this method has a reason to exist. For the Bark() method it could be The dog has to bark every day, otherwise it will get depressed and violent.
Last but not least we need an answer to "how". This one can be very hard to write and not all methods need it answered. You need to understand the "how"-question as a question about the workings of the method in non-technical terms. So the answer to the "how"-question on the Bark() method could sound something like The dog can not bark if it is eating or drinking, so if it does, it first needs to spit it out.
To make sure that all three questions get answered as often and detailed as possible and needed, we can use a simple scheme in the XML comments. Here is an example of such a scheme.
/// Makes the dog bark out loud. (what)
/// The dog has to bark every day, otherwise
/// it will get depressed and violent. (why)
/// The dog can not bark if it is eating or drinking,
/// so if it does, it first needs to spit it out. (how)
if (IsEating || IsDrinking)
By using the same scheme every time you comment, it get’s easier to write and understand and the code gets well documented. It is not important what the scheme looks like as long as the three questions get answered.
Remember that you don't need a reason to answer all three questions - you need one not to. As soon as you get that rule under your skin, it gets easier to uphold every time and before long it gets part of the daily coding routine.