Name your variables carefully, don't fall in the "cnt" trap
Prahlad Yeri
Posted on January 8, 2021
I'd like to share a thing about my programming experience with you guys. A long time ago, being a lazy programmer, I used to name variables in a generic manner without much care for detailing. For example, cnt
will be a standard thing when I want to store a running total inside a loop:
var cnt =0;
..
..
cnt++; //inside a loop
..
..
console.log("Total processed:", cnt);
But what if I needed another counter inside an inner loop? So, that become tcnt
(short for "temporary counter"!):
var tcnt = 0;
And if I needed more, it will be ttcnt
, tttcnt
, etc. and so on. This approached worked for getting the code up and running in a short time but the problem occurred when I needed to change this code in future. If I needed to add a loop or some other construct somewhere and required a numeric variable, I'd add yet another cnt
and the whole thing would fail in testing (because there already was another cnt
which was now rewritten due to this new variable)!
After a few times this happened, I realized that I'd be a much wiser strategy to name the variables depending on what they actually did rather than some numeric name. For example, tot_processed
, cnt_pending
, cnt_updated
, etc. This will give you a good idea of "what" this counter is holding, so there is less chance of it getting confused with another variable in code later.
Posted on January 8, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 19, 2024