Often, when I am initializing something I have to use a temporary variable, for example:
file_str = "path/to/file"
file_file = open(file)
or
regexp_parts = ['foo', 'bar']
regexp = new RegExp( regexp_parts.join('|') )
if I am using a dynamic language, **I wonder if I should reuse the same variable instead:**
file = "path/to/file"
file = open(file)
regexp = ['...', '...']
regexp = new RegExp( regexp.join('|') )
The idea is that *by reducing the number of variables in scope I reduce the chances to misuse them*. However this sometimes makes the variable names look a little weird, as in the first example, where "file" refers to a "filename".
I think perhaps this would be a non issue if I could use non-nested scopes
begin scope1
filename = ...
begin scope2
file = open(filename)
end scope1
//use file here
//can't use filename on accident
end scope2
but I can't think of any programming language that supports this.
**What rules of thumb should I use in this situation?**
* When is it best to reuse the variable?
* When is it best to create an extra variable?
* What other ways do we solve this scope problem?