4.5. Variables with Numeric Suffixes

When writing programs, you might need multiple variables that store the same kind of data. In those cases, you might be tempted to reuse a variable name by adding a numeric suffix to it. For example, if you’re handling a signup form that asks users to enter their password twice to prevent typos, you might store those password strings in variables named password1 and password2 . These numeric suffixes aren’t good descriptions of what the vari- ables contain or the differences between them. They also don’t indicate how many of these variables there are: is there a password3 or a password4 as well? Try to create distinct names rather than lazily adding numeric suf- fixes. A better set of names for this password example would be password and confirm_password .

Let’s look at another example: if you have a function that deals with start and destination coordinates, you might have the parameters x1 , y1 , x2 , and y2 . But the numeric suffix names don’t convey as much information as the names start_x , start_y , end_x , and end_y . It’s also clearer that the start_x and start_y variables are related to each other, compared to x1 and y1 .

If your numeric suffixes extend past 2, you might want to use a list or set data structure to store your data as a collection. For example, you could store the values of pet1Name , pet2Name , pet3Name , and so on in a list called petNames .

This code smell doesn’t apply to every variable that simply ends with a number. For example, it’s perfectly fine to have a variable named enableIPv6 , because “6” is part of the “IPv6” proper name, not a numeric suffix. But if you’re using numeric suffixes for a series of variables, consider replacing them with a data structure, such as a list or dictionary.