Variable name style


What’s your opinion?

I tend to like single-letter variable names e.g. i, j, k for indices, w, h for width and height, s for any string, t for time, etc.

Sometimes when I use meaningful / long names, I end up masking an existing function unintentionally (like sum) and then I would end up scratching my head why sum doesn’t work anymore…



This problem of accidentally masking an existing function with variable happened to me several times (and I probably scratched my head in a similar region). I guess that the IDE could help for this.

Another recurrent error I make is to mix the function definition styles: If I forget the function keyword then the error message is usually not very helpful to spot the problem.


My opinion, and I think the general opinion in many other languages, is that being a bit more descriptive can make the code more readable and self-documenting.

In your example, instead of using s for any string, why not use a name that describes what the string is? Such as column_title. Instead of t for time, use e.g. arrival_time. Instead of w and h, use beam_width and beam_height, etc. (And please never use l as a variable name, since it’s so easily confused with the digit 1 :slight_smile: )

As for masking existing names, I would argue that sum is perhaps not a “meaningful / long name”. I might wonder: Sum of what? With a more descriptive name like distance_sum, there would be no conflicts.

With that said, I think short or single letter variables are acceptable in several circumstances. Mainly when the context is so small that there’s no room for confusion. For example in anonymous functions like this:

sort(rand(1:100, 10); by = n -> n % 10)

Another situation is functions where the argument has no real meaning by itself, like sqrt(x).

Also, if the code consists of dense formulas with repeated use of variables, it might make the code more readable to shorten the names (in this case, w and h might be preferred over longer names).


in many other languages

I think the style varies quite a lot with the language paradigm.

For OO languages, data member plays a major role and accessors to these fields usually mimics their names. As a consequence field names (and accessors) have to be as meaningful as possible. For functional languages, types and functions names have to be meaningful and function arguments, which are always very close to function names, do not need have explicit and long names.

As Julia being a multi-paradigm language this question makes sense. Reading Julia sources, the most common style looks functional to me with a lot of short functions with explicit names (and types) and anonymous arguments. Close to Haskell style for example. This have the benefit to avoid the accidental function masking name issue.

I agree that l should be avoided :slight_smile: