Avoid Similar Variable Names
- One minute read - 201 wordsA convention I see in Ruby tests are variable names like this:
user_a = create(:user, last_log_in: today)
user_b = create(:user, last_log_in: last_year)
The idea is “we need two users to compare behavior against, so let’s make User A and User B.” In this post, I’d like to argue for variable names like this:
frequent_user = create(:user, last_log_in: today)
unengaged_user = create(:user, last_log_in: last_year)
frequent
and unengaged
are not literal suggestion, but rather representatives
of an idea. That idea is that such variables are visually distinct and carry
more meaning.
Visually Distinct
Humans look for patterns. When you squint, user_a
and user_b
look almost
identical. Throughout the code these variables may be referenced many times.
Each time, the code reader has to visually parse them. It’s much easier to
tell frequent_user
and unengaged_user
apart.
Carrying Meaning
When distinguishing the two objects, there’s almost always some context you can use to impart meaning.
If it’s users with distinct permissions, try admin
and reader
rather than
user_a
and user_b
. Items in a state machine, try complete_order
and
returned_order
rather than order_a
and order_b
.
I’d rather have variable names that look different and tell us why they are different than be perfectly telegraphing their composition.