Posted on May - 04 - 2010
Naming Convention Part 2: Purpose of a Variable
First part:
What is a variable actually? Simply it’s a container that has a name. The best practice creating and using variable is to stick a name to a single purpose only.
Say we have some chemicals stored in some bottles and we put a tag on each bottle with the name of the chemical it contains. Now if a chemical is used up, a bottle gets free; will you use it for a different chemical without changing the tag? Think what might happen in that case, you will need to remember when you used that bottle for what and the tag fails to help you. So what is the purpose of the name tag if it doesn’t help you to know what the bottle contains?
When you are going to build a wel-managed software, you should not use the same name for different purposes. If the purpose of a variable is a single thing, then you can easily tell what type of data you saved in it a million lines ago in your code. Here is a dirty example in PHP:
$results=GetCustomers(); //returns an array of customers
…
…a million lines
…//$result variable is freed.
…
$results=GetProducts(); //returns an array of products
…
…a million lines
…two million lines
…
foreach($results as …)
….
…
Now look at the ‘foreach’ block! You need to improve your code after 1 year, and you came across the ‘foreach’. You cannot tell immediately what is in $results: products or customers?
But if you had used two variables called ‘$allCustomers’ and ‘$allProducts’, there would be no confusion in your code. They would serve for a single purpose each.
Second Part:
Now a purpose should have a single variable only. Like a chemical may have two names in different disciplines. If you have two bottles containing the chemical and tag them differently, it will make you slower than if they had the same tag as long as the chemicals are the same. In software engineering, the problem goes bigger.
If you have an array of customers, don’t use different names in different places for them (if not needed). Like in a function you used ‘$allCustomers’, in another ‘$customers’, another ‘$onlyCustomers’. This lowers readabilty, for others, and for YOU!









































