Sunday, November 3, 2013

Is variable named "i" fine ?

At many places we see variable named "i","j","c" etc scattered every where around the code; in all the methods. The obvious question that rises is "is such short variable name (e.g., i,j,k,c,k etc) fine?". Many people says that the variable name should ALWAYS be long and descriptive but you sense of "code smell" says that it is fine. But some people says that it is fine. This might actually confuse you.

Here is the  rule to answer answer the above question:


Uncle Bob's Rule:
For variable:
           Longer the scope, the longer the name should be.
For function/methods and classes:
           Longer the scope, shorter the name should be.



Lets understand it with an example of variable name:

The code below with variable named "i" is fine because the scope of "i" is very short :
    private static int getSumOfCharsInString(String name)
    {
        int sum = 0;
        for (int i = 0; i < name.length(); i++)
        {
            sum += getIntValueForChar(name.charAt(i));
        }
        return sum;
    }


But here the following code with variable named "c" is NOT FINE because the scope of the variable named "c" is very long(Its up to you to decide how much length to be considered as "long"). The variable named "c" should be refactored to something meaningful and long.
int main()
{
    char c;
    void getfile();
    void getfname(char []);
    char temp[MAX];  
    getfile();
    getfname(temp);
    if ( source != '\0' && html != '\0' )
    {
        fprintf( html, "%s", "" );
        fclose( html );
        fclose( source );
        printf("\nThe file is now created");
    }
.
.
.
    do
    {
       c = getc( source );
       if ( c == EOF )
       {
          break;
       }
       else if ( c == '<' )
       {
          fprintf( html, "%s", "<" );
       }
       else if ( c == '>' )
      {
          fprintf( html, "%s", ">" );
      }
      else if ( c == '&' )
      {
         fprintf( html, "%s", "&" );
      }
      else
      {
         fprintf( html, "%c", c );
      }
  }
  while ( c != EOF );
.
. 
}