I admit I use one letter variable names in my code. But which names? Here's what I use in for loops:

# rg 'for \(let . ?=' 
#     | perl -pe 's/.*let //g' | perl -pe 's/=.*//g' 
#     | sort | uniq -c | sort -nr | head

509 i
132 x
122 y
118 r
 57 t
 53 q
 47 j
 43 s
 31 e
 14 k

My naming conventions:

  • i, j, k: generic index
  • x, y, z, w: coordinates
  • q, r: col/row grid coordinates
  • r: region number
  • r: range or radius
  • t: triangle number
  • t: time index
  • s, e: sides/edges of a polygon
  • w, h: width/height

Outside of for loops, rg 'let . ?= | grep -v for' finds that I also use these conventions:

  • a, b: endpoints of a range or line segment
  • a, b, c: equation for a line, or quadratic formula
  • v: generic value
  • p: point
  • t: time
  • d: distance
  • d: reference to svg <path> d= attribute
  • g: reference to svg <g> element

If I were working in a team I'd follow their naming conventions, but for the most part I am writing the code for myself, so I'm ok with short variable names like these. The common objection is that I won't understand the code six months later, but I haven't found that to be an issue. These are all local variables inside a function, and I tend to use the same conventions across projects.

Labels:

3 comments:

Gabriel Ferrer wrote at January 04, 2023 8:38 AM

This seems like a good practice to me.

Variable name length should be proportionate to scope - a loop index variable has limited scope, and can and should be short.

Parameter names should arguably be longer, in that they should describe clearly the role of the parameter in the function to make it easier for clients to use the function correctly without looking at the source code. Same goes for instance variables.

ëRiC wrote at January 05, 2023 3:41 AM

Naming conventions are good. Most of the time I'd insist on being able to grasp where things are coming from. If you see at one glance where p is created and where it's consumed I wouldn't make a fuzz about it.

If it's unnecessary though and a more descriptive var name wouldn't make lines unbearably long and cluttered: make it so right away :)

Warren Marshall wrote at July 02, 2023 2:40 PM

Loop iterators are typically not important, they're just a vehicle to get you from A to B. Single letters are fine. :)