Variable Names
As a preface, this post is going to focus on the Ruby programming language, however a lot of these ideas are prevalent in many other languages as well.
The Importance of Variable Names
Having clear variable names makes it easier for you, and others that read your code, know what each variable is doing. This in turn makes it easier to understand what your code itself is doing. Lets take the following example of names.
If we wanted to perform some operations on these arrays later in our code, would you know exactly which methods “x” has available? Its just “x”, and if we write hundreds of lines of code before we use the variable, it would be easy to forget. However, we know that “num_array” is an array of numbers. We know that we can iterate through with methods such as “each”, “map”, “select”; as well as other methods available to arrays. However, on top of knowing that “num_array” is an array, we also know what is inside that array. If we call
it is hard to choose a name for the variable inside of the pipes. However, its easy for us to choose a variable name for inside the pipes for “num_array”, because we know what is inside “num_array”.
Types of Variables
- local: a variable either declared in a function or an argument passed to a function
- Global: start with “$”. They are available throughout all of your code.
- Instance: declared within an object that belongs to the instance of the object, begin with “@”
- Class: a variable declared in a class that is shared among all objects of that class. Only one copy of a particular class variable exists for a given class
Tips on Naming Variables (And Methods)
- Be specific about names
- This is the difference between “x” and “num_array” from the beginning example
- Try not to use 1 letter variable names such as “x”, “i”…
- Variable names should describe what they are in enough detail that you don’t need to second guess what type of object they are, and what information they hold.
- Method names should describe whatever operation or algorithm they are performing.
- Take time if you need to. You won’t always think of the perfect variable name immediately and it’s ok to take some time to think of one. In the long run it’ll help you with reading and understanding your code.
Try It Yourself
I hope this helps you in your future coding endeavors. Try out these tips the next time you’re coding!
Get Jesse McReady’s stories in your inbox
Join Medium for free to get updates from this writer.
Originally published at gist.github.com.







