Local Variables Are Bad

RefactoringImprovingTheDesignOfExistingCode seems to suggest that LocalVariablesAreBad. Are they really? Why? When are they okay?

Some local variables are bad. Some are good. Local variables in general are certainly not bad.

Local variables are bad when they are unnecessary. Example:

 int foo() {
    int ret;
    ret = bletch();
    return ret;
 }
There are a few good reasons for local variables:
  1. to accumulate values in a loop
  2. to keep from having to evaluate the same expression several times, and is a speed optimization. (But remember, this is optimization.)
  3. to give a name to a value so that the program is easier to understand. (See also IntermediateValues)
  4. to save the old value of an expression when the expression depends on variables that change.
  5. to implement the ResourceAcquisitionIsInitialization idiom (resources are acquired as a side-effect of object instantiation, and released as a side-effect of object destruction)

The first four are explained in SmalltalkBestPracticePatterns. As it says (page 103), "The examples are taken from Smalltalk, but the discussion applies to any language with procedure-scoped variables".


Theory: By eliminating local variables (or, more precisely, non-initialization assignments thereto), you approach FunctionalProgramming (which, as everyone knows, is a GoodThing (-: ). -- BillTrost

SingleAssignmentVariables? have no conflict with FunctionalProgramming, so this theory doesn't apply to them.


  1. to provide visibility of intermediate values of calculations while debugging.

This is a lifesaver when debugging algorithms in LegacyCode in which you have low confidence. Optimizing compilers wreak havoc on this concept, but in CeeLanguage the volatile keyword resolves it. One debugger mangled the locations of parameters passed on the stack, so locals provided visibility to function parameters.

Yeah, the only hassle there is when you are debugging something like an interrupt handler. You can't do a lot of local variable creation and assignment because of latency issues. Oh, well.


I'd like to add that we are talking about local variables as opposed to no variables at all. Not about local variables as opposed to instance variables (which was my first idea when I read the title). In the latter case, one should make them instance variables only if they are part of the state of the object.


EditText of this page (last edited August 11, 2003) or FindPage with title or text search