Recipe For A good Variable name

Abbey kumapayi
2 min readJan 4, 2024

--

Naming variables in programming is one of the difficult skill to master as a developer, not everybody pays attention to consciously improving this skill. Proper variable naming helps make a code more readable. This blog post does not focus on naming conventions or practice instead it focuses on ways to come up with good variable names.

When coming up with variable name the following should be put into consideration

Context

We should be always be aware of the context of a variable — where it is declared and where it is used. The difference between naming variable getAge and getUserAge is context. To name a variable getAge means it is directly meaningful to where it is declared and used because it sounds generic. When I see a getAge function the first question to ask is “get the age of what?”. If this function is in a file named user.js or is a method to a User class then we can answer the question above.

Moreover, if we have a getAge function declared in place that doesn’t put it in any context or is going to be used anywhere outside of the file it is declared, it is better to make the name less generic and add more description to the name e.g. getUserAge, getCustomerBirthday etc.

Intent

A variable name usually functions should always convey the intent of the variable. At a glance, one should be able to know the purpose of a function. Function names should denote action and action type using suitable verbs like get, handle, save, and so on depending on the purpose of the function. A function that returns a value should probably start with get . Good examples are getUserData, handleSubmitError, saveDataToStore

Consistency

It is better to stick with a naming pattern when naming variables. For instance, if write a function to get a list of books from an API and you decide to name your function fetchBooks, it is only ideal that when you decide to write another function that gets news from an API to be fetchNews. Using a name like getNews would mean a lack of consistency. Although it doesn’t break the codebase in any way, but it keeps thing simple for everyone involved and set a naming pattern for those type of functions in your codebase.

Content

The content in a variable should be something you consider when naming a variable. A simple example of this is declaring a variable that stores a list of books, a good name would be books or bookList. A variable that stores a list of book authors would be named bookAuthors or bookAuthorList. The name should indicate if it holds one data or more.

--

--