Page 1 of 1

/* Comments */

PostPosted: 21 Feb 2013, 15:31
by Ursego
Comment your code if it is not completely straightforward, or when you want to title different fragments of your script.

That will not only help other developers to understand your code, but will also help yourself: will you remember what your tricky code does after a few years?

Don't comment in other cases.

Don't leave comments if they are not really needed (like 'Declare variables:' just before a variables declaration section and 'Call function XXX:' just before calling function XXX). But really foggy fragments were absolutely comments-free!

Comments can help you not only understand existing methods, but also write new ones: just after creation of a new function, write a comment before each future code fragment, performing a different logical task (as if you would comment an existing code), and AFTER THAT begin to write executed code. Below is an example of an initial skeleton (built of comments!) for a function which calculates a new balance for a customer (also pay attention that we can avoid articles "the" and "a" in comments - that shortens them):

Code: Select all
private decimal calcNewBalance (integer customerID, decimal amountToAdd)
   {
   // Validate parameters:
   
   // Retrieve existing balance of customer:
         
   // Retrieve their allowed overdraft:
         
   // Calculate new balance:
         
   // If it exceeds allowed overdraft then return original balance:
         
   // If this code reached then new amount is ok - return it:

   }

An that moment it's easier to concentrate on the "upper-level logic" - you simply describe what the function is doing using the regular human language. After the "comments skeleton" has been created, start writing executed code (each fragment just after its corresponding comment).This method decreases chances of having to re-write code.