1

Say you have some basic code where similar operations will take place in nearby lexical scopes. Take for example some simple pseudo code:

variable = "foo"
# Do something with variable
if (True) {
    variable = "bar"
    # Do something else with variable
}
for i in range 1..100 {
    variable = i
    # Do another thing with variable
}

Say that in each scope, the variable is used for a distinct, but similar task and thus the name "variable" is appropriate in each case. What is the best practice in this case for naming? Should you use the name "variable" each time? Increment the name such as "variable1", "variable2", etc.? Or something else entirely?

jkeuhlen
  • 121

5 Answers5

4

If the variable in question represents the same thing for both functions, I can't see why it would be a problem. If you're arbitrarily using variable to mean "any variable within a function that can do anything" then yes, it is a problem. Name your variables in the context to which they are used.

4

There are two entirely different things at play here: variable reuse and variable name reuse (redeclaration.) Your sample pseudocode does not make it clear which one of the two cases you are referring to, so I will mention both.

This is variable reuse:

int i = 5;
for( ;; )
{
    i = 3;
    ...
}

This is variable name reuse:

int i = 5;
for( ;; )
{
    int i = 3;
    ...
}

Variable reuse is very, very bad and it should be avoided at all costs because it leads to spaghetti code. Code may one day be added after the for loop, expecting i to hold 5, and it may be very shocked to find out that it doesn't. People reading this code will assume that you are replacing the value of i in order to use the new value after the loop. Decent compilers will give you a "variable reuse" or "variable scope too broad" warning if you do this, but they may not always be able to detect it, (in the case of a for loop, they cannot, because you may be doing it intentionally,) so it is best to not push your luck.

Variable name reuse is perfectly fine, and as a matter of fact desirable under certain scenarios. For example, variable name reuse guarantees that within the for loop you cannot accidentally refer to the outer scope i, because it has been redefined and therefore it is now inaccessible. (Unfortunately C# does not like that, but most other languages have no problem with it.)

I would not answer "it is good or bad depending on what your peers say", because you may be asking this question on stackoverflow precisely in order to have arguments when discussing this matter with your peers.

Mike Nakis
  • 32,803
1

If the variable is something simple and clear, like i, count, sum, go ahead and reuse it.

If the variable is central to the method, like calculatedResult, or you are in a series of if/else blocks (or blocks all ending in return calculatedResult), reuse it.

But if the blocks are not mutually exclusive, and control flows from one to the other, it might be clearer to not reuse the same variable name. For example, if you are doing a series of SQL queries, I might go (Java-ish syntax)

if (theyCareAboutPeople) {
   peopleQuery = "SELECT * FROM people WHERE blah blah...";
   ResultSet people = mySqlDriver.execute(peopleQuery);
   // do something with people
}
if (theyCareAboutAges) {
   ageQuery = "SELECT * FROM ages WHERE blah blah...";
   ResultSet ages= mySqlDriver.execute(ageQuery );
   // do something with ages
}

Note that I used meaningful names, like "peopleQuery" and "ages", instead of calling all the queries "query" and all the results "result". IMO, this is slightly clearer, but YMMV.

user949300
  • 9,009
0

Reusing a variable is bad, because a compiler that would normally warn you about uninitialised variables etc. can't warn you, because at the time of the second use, the variable will be initialised.

Reusing a variable name is usually not a problem.

You may get compiler warnings if you create a variable with the same name as another variable in an outer scope. With good reason, because that is going to be confusing and error prone. Avoid it whether you get warnings or not.

You may have problems with a debugger that thinks there is a dozen variables with the same name and cannot tell you which one you are using right now. This is a problem of the debugger and should be fixed, but if you run into the situation, you may choose to write code that is more debugger friendly.

gnasher729
  • 49,096
0

Specificity - don't use a variable named variable unless it refers to something specific, like variable timing on an engine. Just don't do it.

In a given context:

Do not re-use variable names in a given context for different purposes. In a function, don't make variable = 'foo' for use as a string then later in the function make variable a numerical index in a loop - that's bad practice and will return to bite you in a big way.

You can re-use variable names in a given context for the same generic purpose, but consider using a new variable to avoid confusion:

var i, j, myarray = [];
for( i = 0; i < 100; i++){
//
   mayarray.push[ i ];
}

for( j = 0; j < 1000; j++){
   // something with j
}

You could technically re-use i for the second loop instead of using a new variable, j, but I would avoid re-use in this case because it can lead to confusion reading the code and could introduce bugs later on.

Outside the same context

We all re-use common variable names like i for loop indexes; that is good practice and improves readability as long as they are not in the same context.

If you are thinking about re-using a non-generic variable name, like partNumber, limit their re-use to places where they refer to the same logical thing in your code as other uses of the variable. Otherwise it can lead to confusion in your code.

Your application has a schema internally that shows the data you are manipulating. Map that schema to your variable names, use generic variable names for generic purposes, and be aware of your contexts for variable re-use.

Robert Munn
  • 1,309