Effective Variable Naming Tips
Variables happen to be the very first things we come across while learning any programming language. As elementary as it is, sometimes giving effective and concise names to local variables, functions and classes as we code, can be tedious and challenging. This can be further compounded especially when we are under pressure, or chasing tight deadlines hence the temptation to gloss over or end up with something faster to type but less meaningful.
How we named our variables do not interfere with the program expectations such as usability, efficiency, reliability and flexibility, so what the heck's the matter? ๐คจ
Of course, our code is not just for the computer but also for ourselves and other developers' understanding. However, we always desire a situation where someone else looking at our code can understand the intentions rather quickly and be focused on providing valuable feedback in the case of peer code review or when we eventually come back a few weeks to months later to that same piece of code. Things will go much more smoothly for everyone involved if our variables, classes, and functions are named with an emphasis on simplicity and intent.
We mustn't take the way things are named in our program lightly, as it has a significant impact on the readability and quality of the source code. A readable source code is also a prerequisite for maintainable software which can lead to successful collaboration among developers. Sometimes, poorly named variables might mean the difference between a fellow developer immediately understanding what everything does and not knowing where to start.
Naming Tips
Even though there are no absolute guidelines that can be used in every circumstance, here are some tips that are helpful when coming up with clear, concise and consistent variable names.
- Use clear and expressive names
Most times clarity is often sacrificed for speed in a bit to be more productive by trying to reduce the number of keystrokes that needs to be hit to craft out a variable name thus ending up with names like fn
, ln
, tr
, T_NUM
, etc. It is no doubt that very shorter names like those above are quicker to type and tend to get you up to speed but the reality is that the few extra minutes you spend carefully selecting variable names could save you hours if you or others later revisit the old code. Variable names should be as clear and expressive as possible to easily convey their intent, purpose and the type of data they hold to the reader.
The simplest way to come up with a clear and meaningful name for your variables is to close up the spaces between words or replacing with an underscore depending on your naming pattern preference.
Example:
const lastAppointmentDate = 0; // Last appointment date
// or
const last_appointment_date = 0; // Last appointment date
You may notice, in the first case, I simply remove the spaces and capitalize each of the words. This is actually because am using the camelCase pattern. If you prefer snake_case then the second approach is for you.
- Be consistent
It is common knowledge that different teams do adopts different naming conventions and some programming languages and frameworks too have their generally acceptable naming conventions. For example, functions and classes in C# and Java are named with PascalCase while variables take camelCase unlike in PHP where functions are in camelCase and snake_case is predominant for ordinary variables.
Also, quite a good number of programming languages recommend upper snake_case (screaming snake case) for constants like
const MAX_CONCURRENT_CONNECTION = 200
Avoid using different naming patterns within the same project for example using camelCase and snake_case to name functions and variables or Pascal and camelCase for Classes. Throughout the project, all variables, functions, and other things should be named using the same conventions.
Not advisable ๐
let next_appointment_date = new Date(Date.now() + (48 * 60 * 60 * 1000)); // adding 2days (48hrs) to the current date
let totalCharge = 5000;
Good ๐
let next_appointment_date = new Date(Date.now() + (48 * 60 * 60 * 1000)); // adding 2days (48hrs) to the current date
let total_charge = 5000;
// or
let nextAppointmentDate = new Date(Date.now() + (48 * 60 * 60 * 1000)); // adding 2days (48hrs) to the current date
let totalCharge = 5000;
If you maintain a consistent naming strategy, your codebase will be simpler to understand and require less thought from fellow developers. ๐
- Avoid Abbreviations
We all yearn to be fast, reduce our turnaround time, and close out on as many tasks as possible. As such, the greater tendency to abbreviate as extra keystrokes on the keyboard is often considered anti-productivity. This is not a valid reason. Abbreviations in code are like a double-edged sword; they could breed confusion and on the other hand, could make names shorter and clearer. Try to get rid of abbreviations in your code. However, if you happen to abbreviate variables perhaps the resultant name is too long, ensure the abbreviated version is clearer or still able to convey the meaning and intention of the variable to the reader.
Note, abbreviating functions and classes are not recommended either. If a function name is too long and needs an abbreviation, it's a true indication that the function may be doing more than one sort of thing and hence need refactoring.
Not advisable ๐
let daysSLV = 3;
let avePerSec = 100;
Good ๐
let daysSinceLastVisit = 3;
let averagePerSecond = 100;
Not advisable ๐
function calculateInterestAndPenalty(){
...
}
Good ๐
function calculateInterest(){
...
}
function calculatePenalty(){
...
}
When there is a need for abbreviating variables, it's essential to ensure there is enough context and that the abbreviations are globally and generally acceptable. See the example below.
โ let conn = "";
โ
let mongodbConn = "";
conn
is a popular abbreviation for connections, which could be network, database or any other connection string. The bottom line is, someone in Finland should be able to read and understand your variable without guessing as someone in the USA. ๐
- Avoid names with just one letter.
The readability and comprehension of the code may be hampered by single-letter variable names. It can be challenging for others to comprehend the function of the variable and how it is utilised in the code because they frequently give no information about what the variable contains or what it is used for hence increasing the mental tax on the reader.
Not advisable ๐
let p = await databaseContext.products.findById(productId);
Good ๐
let product = await databaseContext.products.findById(productId);
Don't go overboard, after all that, though. For throwaway variables, such as index variables in loops, etc., "i" "j" and "k", etc work perfectly fine.
Conclusion
Reading code is already a tough process, using ambiguous names that will require guessing only make this process tougher. Good and descriptive names among other benefits help simplify searching and finding in a large codebase. Our variable names, including functions and classes, should be simple, clear, consistent and self-explanatory thus also taking away the need for explicit documentation.
It is worth noting that having clear and meaningful variables does not translate to extreme verbosity. Longer or highly verbose variable names tend to defeat the purpose of clarity hence the need to stay within a reasonable length long enough to be descriptive and understandable.
Do you have other tips you could share? They're very much welcome in the comment section.
Subscribe to my newsletter
Read articles from Kufre Okon directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Kufre Okon
Kufre Okon
I am a result-oriented, detailed and passionate full-stack software engineer with a niche in technologies around the C#, Java, PHP and JavaScript ecosystems and a significant focus on enterprise solutions. I found pleasure and inspiration in trying things out, appreciating the positive outcomes and learning from my mistakes.