Programming Practices – Using Same Variable Name in Different Scopes

namingprogramming practicesscopevariables

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?

Best Answer

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.

Related Topic