Jake Worth

Avoid Similar Variable Names

Published: February 14, 2022 1 min read

A convention I see, particularly 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)

Swap these out for user_1 and user_2, or user_one and user_two, and you have a very pervasive practice. I think this 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 that variable names like this are preferable:

frequent_user = create(:user, last_log_in: today)
unengaged_user = create(:user, last_log_in: last_year)

frequent and unengaged are not literal examples, 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.

✉️ Get better at programming by learning with me. Subscribe to Jake Worth's Newsletter for bi-weekly ideas, creations, and curated resources from across the world of programming. Join me today!

Blog of Jake Worth, software engineer in Maine.

© 2022 Jake Worth.