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('|') ) However, I like to reduce the scope my variables to the smallest scope possible so there is less places where they can be (mis-)used. For example, I try to use for(var i ...) in C++ so the loop variable is confined to the loop body.
In these initialization cases, if I am using a dynamic language, I wonder if I shouldam then often tempted to reuse the same variable instead: in order to prevent the initial (and now useless) value from being used latter in the function.
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?