CSC/ECE 517 Fall 2009/wiki3 14 rd: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
Line 229: Line 229:
Finally have someone else who has never seen the code go over it. The point of this is if they have any questions about any parts of your code you should comment that part better.
Finally have someone else who has never seen the code go over it. The point of this is if they have any questions about any parts of your code you should comment that part better.


==Conclusion==
 


==References==
==References==

Revision as of 19:58, 18 November 2009

Principle of Self-Documentation

Introduction

A good code can be defined as a code that has a good structure and design, correct algorithm used and a good flow to the program. Good code is not replete with question mark colon operators and pointer arithmetic, or at least not when the code doesn't need to be optimized to save a few seconds every few months of operation. The algorithm may be too complex and function names may be esoteric . This makes readablility of the code an issue. Thus the defenition of a good code involves a good self documenting sturcture and invloves many comments to aid the user or developer in understanding the code .

Self-Documentation

Self documentation of the code invloves using two methods

  • 1. Coding style

One of the major goals when embarking on a development project is to structure the application such that the code documents itself. Thus if all the comments disappeared , the code should still be understandable to the developer

  • 2. Commenting

To make the code completely understandable the use of good code documentation is not enough . There is the need to give explanation of the working and the flow which may not be easily derieved form the code itself .Explanation of an algorithm can only be done with the use of comments.

Coding Styles

The biggest concept of self documentation is the naming itself .The is basically two rules for that one has to follow in order to ensure that the code is self documenting .

  • If it looks like a cow and acts like a cow, call it a cow.
  • Once you call it a cow, make sure you always call it a cow.

In other words , the naming should be as meaningful as possible and the developer should stick to it trying not to step out of convention. The abbreviations used in the code should also be those that are commonly accepted .

naming message as msg and sticking to it is a good coding style
naming message as mesg,msg,mess,msge throughout the code will make understanding of the code difficult

Methods

When trying to name a method , try to describe the intent in the name itslef . This enables the developer to understand the code and the use of the function call in the program.

user.GetID();
user.Get();
product.GetAvg();

Understanding the method calls by just looking at the code is difficult .The reader to actually drill into the logic to determine what the method actually does.

user.getcustomerID();
user.Getnextcustomer();
product.GetAveragePrice();

The method calls makes for explanation of the logic more clear . The function names explain themself what the call invloves.

Another advantage to implementing this type of specific naming in your code is that it can give you an excellent heads up when a method is trying to do too much.When you are attempting to name a method and you find it difficult because of the scope of the method you should definitely examine it and see if you can break it up into smaller more specific pieces.

Variables

Simliar to the principles for naming methods, name your variables explicitely as to what they accomplish. The worst case scenario of this would be using a variable "d" which tells me absolutely nothing. Slightly less harsh would be using "dt, dte, or date". What is most beneficial to the reader is using a name like "CurrentDate" or "MeetingDate".

Another example is the use of i,j in looping sturctres .

for i = 1 to 7

The code suggestst that there is looping structure here ,but nothing more

for dayInWeek = 1 to NUM_DAYS_IN_WEEK

Thus by the use of specific variables and prameters the loop structure is now clear in terms of its use in the code.Although the coding style becomes more verbose , it will aid in better understanding of the code even for the developer when he returns to add or extend the code .


Commenting

In software development, in-code documentation is a very important aspect of the code. Program comments within and between modules and procedures usually convey information about the program, such as the functionality, design decisions, assumptions, declarations, algorithms, nature of input and output data, and reminder notes. Almost all the source code will need to be referred back in back in the future or it might also need to be reused. In any case the document that is provided is like a specification or a literal form of the code for any reader using it in the future. Without a good documentation, the reader will end up wasting a lot of time understanding the code or make dangerous assumption and misinterpret the code.

Even while documenting a code we need to take care that we neither comment the code way too much nor should be too less that its meaningless to the reader. Lets first take a look take a look at the different approaches to commenting; too much and too little:

  • Too Little
#include 
#include  
//This is a function
int calculateDistance(int x, int y){
     . . . .} 
//Main function
int main(){
     int x=0;
     int y=2;
     calculateDistance(x, y);
     printf("SUCCESS");
     return EXIT_SUCCESS;
}

The above comment has way too little information for the reader to make any meaning out of it.

  • Too Much
/*These are two pre-defined header files that
I've included I'm going to be using printf()
from stdio.h and then I'll be usingEXIT_SUCCESS
from stdlib.h*/
#include 
#incude 

/*This function takes in the two variables
(x and y) and calculates the Distance
between the two. In the end it will return an
integer.  I thought I'd include a few error
checks in the code but then decided
against it. They'll be added in version 1.1 */
int calculateDistance(int x, int y){
    . . . .
}

//The function where the program starts.
int main(){
    //These are the two variables use.
    int x=0;
    int y=2;

    //Call the the calculateDistance function
    calculateDistance(x, y);
    //Prints that the function was a success
    printf("SUCCESS");
    //Exits the program
    return EXIT_SUCCESS;
    //End of the main function
}

And this code has way too much information. This is unnecessary and makes the program look huge and cluttered up.


Four major types of comments

  • Code Commenting - This refers to writing descriptive variable names that are self explanatory.
function addUserToDatabase(userName, userAge)
  • 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.
function calculateHitPoints(cUser) {
    var nStrength = document.getElementById("enemyStrength").value; // grab current enemy strength

    // subtract user size : small = 1, medium = 2, large = 3
    var nDamage = (nStrength * 3) � cUser.nSize;
    return cUser.nCurrentHitPoints � nDamage;
}
  • Function Commenting - This type of commenting is found on the lines above a function, and reveals all of the necessary details about that function.
/*
 * Summary:      Calculate hitpoints after attack using formula
 *               new = current � ((enemyStrength*3) � size)
 * Parameters:   cUser � object containing hero's stats
 * Return:       Boolean indicating life or death
 */
function calculateHitPoints(cUser) {
    �
} // end calculateHitPoints
  • 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.
/* 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
Title : 
Author : 
URL : 
Description : 
Created : 
Modified : 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
*/

Tips for commenting

  • Comment each level:

This is the first important rule that you need to remember. 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

Adopting comment standards is important when working with a team. Of course, it is acceptable and even advisable to use comment conventions and tools (such as XML in C# or Javadoc for Java) to facilitate this task.

  • Paragraph Comments:

On top of each block of code that is there in the program, add a comment explaining what exactly the following block of code will do.

// 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();
. . .
  • Align comments in consecutive lines:

If there are codes in consecutive lines of the program, align them such that they start at the same point. This makes the program more readable.

const MAX_ITEMS = 10; // maximum number of packets 
const MASK = 0x1F;    // mask bit TCP 

You can use tabs to align them together. Also make sure you leave a small gap between where the code ends and the commenting begins.

  • Avoid obvious comments:

Avoid obvious comments in the code. This will only clutter up the code and distracts the reader with details that can be easily deduced from the code.

if (a == 5)      // if a equals 5 
   counter = 0; // set the counter to zero
  • Be polite:

Always stay away from making any rude comments to the reader 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.

  • Use a consistent style:

Always use a consistent style of coding. Its always easier for reader to understand the code and documentation if the comments are in consistent style throughout the code.

  • Do commenting as you code:

Its always good to make it a habit to comment the code as you write it. Its much easier to do the commenting it when the code is still fresh in your memory. public void ProcessOrder() {

   // Make sure the products are available
   // Check that the customer is valid 
   // Send the order to the store 
   // Generate bill 

}

  • Comments should always be written as if they for you as much as it is for others:

When it comes to commenting code, think not only about the developers who will maintain your code in the future or reuse it later, but also think about yourself. In the words of the great Phil Haack: “As soon as a line of code is laid on the screen, you’re in maintenance mode on that piece of code.”

  • Always update the comment when the code is updated:

The comment needs to be updated whenever the code is updated. If this is not followed, the comments might end up confusing them and prove to be a curse to the developers rather than helping them. Pay special attention to refactoring tools that automatically update code but leave comments unchanged and hence obsolete in the same instant.

  • The golden rule of comments: readable code:

Your code should speak for itself. Self explanatory code will make the life of the future reader of your code a lot easier.

Calculator calc = new Calculator();
calc.Set(0);
calc.Add(10);
calc.Multiply(2);
calc.Subtract(4);
Console.WriteLine( "Result: {0}", calc.Get() ); 
  • Get a friend to look it over:

Finally have someone else who has never seen the code go over it. The point of this is if they have any questions about any parts of your code you should comment that part better.


References

Tips to commenting your code

Commenting styles

Code Self Documentation

The Art of Commenting

Tips for Commenting

Types of Comments