One of the most minute aspects of writing code is opting when – or when not – to use variables.
It sounds like a trivial decision, right? And in some respects, it is, but the longer I’ve been writing code (or, perhaps a better way to put it), is that the more code that I’ve written and had to maintain, the more my opinion has changed on how frequently I use variables.
After being in the industry for a couple of years, I tried to follow the this rule of thumb:
“Only if I need to use this value more than once, then I will store it in a variable.”
And I still think that’s a decent rule of thumb, but the more I’ve worked with systems that, say, interface with a database, or that leverage multi-dimensional arrays, or that some type of iteration (be it an each
iterator, a foreach
iterator, or something similar), the more I’ve found how storing a variable – even if it’s only going to be used once – can make for slightly more readable code.