Refactoring Perl #6 - Split Temporary Variableby agianni (Hermit)
|on Aug 16, 2007 at 17:12 UTC
This is a refactoring of a common anti-pattern: the inappropriately re-used temporary variable. In Perl, the refactoring looks like this:
Not much of note here, just keep in mind Fowler's exceptions: loop variables or collecting variables are all good. Generally, I don't find loop variables to be all that useful in Perl, and I don't know that I would reuse one anyway. I imagine that Fowler is alluding to something like:
but I don't generally find myself doing that anyway. True, loop variables are rarely going to get you in trouble, as they are usually initialized on each iteration, but it certainly doesn't make the code particularly readable. As such, I'd rather name my loop variables based on what they're actually doing. But I also like $verbose_variable_names, so YMMV.
The upshot is that this refactoring pattern is as much about making your code understandable as it is about avoiding errors that can occur when you reuse a temp variable. If you forget to reinitialize it before the second time you use it (or, say, accidentally delete the line that does), you're in trouble.