On Naming Variables…

Kadir Malak
2 min readOct 18, 2019

--

Photo by Kristian Strand on Unsplash

I used to think that variable names must be as long as possible to be expressive as much as possible. I’m beginning to realize that this thought has a flaw in it: more length does not always mean more meaning. And also I used to stick to a naming convention. I still think that naming convention is extremely important but the notion of convention expanded a little bit for me.

In the following examples, I’ll be giving some examples probably from a certain domain, but the ideas are general.

Long variable names are not always the best choice.

For example, if you’re writing mathematical equations, long variable names hide the overall purpose and shape of the equation.

Short variable names (even sometimes just one letter) is totally OK if the context permits.

In the example above x and y are universal placeholders for two numbers. See the example above.

Sticking to a naming convention does not necessarily mean that you should always follow camelCase, snake-case, or_any_other_case without questioning.

Convention just means that you have some sort of base rules for naming things. As long as it’s consistent and understandable, it’s ok to step out of predefined conventions.

For example, when you’re working with matrices, single-letter upper-case variables are more than OK. When you see them, you recognize.

example1: trainInstances and trainLabels are OK, but we could do better

example2: X is a common convention for instances matrix in machine learning domain, x usually represents a single instance, but just to stick to the camel case convention, we could not use X. It’s misleading now.

example3: Here we’re stepping out of camel case, just not to write Xtrain (seems like a single word). The underscore divides the symbol part and detail part. We could also continue with the camel case like this: X_trainAndTest.

The scope is important. Also when naming variables…

We’re in DBClient class, all is DB related. Prefixing every variable name with “db” or including “DB” in method name is redundant.

When working with templates, to see the whole picture, variable naming may be omitted too.

If a method/function/object/etc is used like a language construct, probably using a long and distracting name is a bad idea (or using a short name is a good idea).

MATLAB or Octave has built-in support for matrix operations. Python, on the other hand, has that functionality via libraries such as NumPy. Here in the code example below, the library is trying to minimize the added syntax needed for matrix operations.

Nowadays, we have ways to remind ourselves the underlying datatypes of the variables. So please don’t write Visual BASIC 98 code.

var counterLong: Long = 0L // this variable's data type is Long

--

--