Writing Efficient Variable Names

Variables are a great way of storing a data to use it in a multiple places, instead of hard coding the data in every section of source code where it is required. Since the day machine language was left and languages that were understandable by humans were introduced, variables were a part of the programming paradigm. Not only this, but also that the variable spacing, memory management was also to be managed, using different data types for data. 
 
In this blog, I will not talk about the data-types, instead I will talking about good variable names that should be used to improve the source code. Just the way comments are a vital part of a good source code, to explain the purpose of code to other programmers without him having to fully go-through all of the source code, similarly a variable name is also a good part of source code as it removes ambiguity from the code; even the developer who wrote the code would not have an idea of what does x means after reading the source code one month later. 
 
Let us take an example code into considerations,
  1. var x = 18;  
  2. var y = Console.Read();  
  3. var z = false;  
  4. if(x > y)
  5.  {  
  6.     z = true;  
  7. }     
  8. if(z)
  9.  {  
  10.     Console.WriteLine("Too much gibberish.");  
  11. }   

The above code makes no sense, for what is the purpose of x, y or z. Although the code runs fine, and there won't be any problem in compilation either. The naming conventions for identifiers is, 

  1. Name must be atleast 1 character to 30 characters.
  2. Name must not contain numbers.
  3. Name can be alphanumeric with no special characters. Number must not come at the first place, and the underscore '_' character is allowed in naming. 
  4. Names of two seperate variables, function and/or classes must be seperate; they should not match.
Let us add another our own convention, "The name must define what purpose it is written for". Now, let us re-write the above code following these rules.
  1. var minimumAge = 18;    
  2. var myAge = Console.Read();    
  3. var adult = false;    
  4. // If the age is above than the minimum requirement  
  5. if(myAge > minimumAge) 
  6. {    
  7.    adult = true;    
  8. }    
  9. if(adult)
  10.  {    
  11.    Console.WriteLine("The code does make sense for what is being done.");    
  12. }  

There are multiple other options and scenarios where using a correct name for the variables describes the actual underlying concept for the usage of the code. 

Ebook Download
View all
Learn
View all