Is it OK to use dynamic typing to reduce the amount of variables in scope?

Posted by missingno on Programmers See other posts from Programmers or by missingno
Published on 2011-11-11T12:35:39Z Indexed on 2011/11/11 18:26 UTC
Read the original article Hit count: 270

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 am then often tempted to reuse the same variable 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?

© Programmers or respective owner

Related posts about programming-languages

Related posts about best-practices