in reply to Re: Coding style: truth of variable name
in thread Coding style: truth of variable name

My general rule is to reuse a variable when the old value is no longer needed

Taken at face value that is terrible advice. A large part of understanding code is understanding the role of variables at any particular point. That is why choosing good variable names is important.

If the role of the variable changes through the code then understanding the code becomes much harder. So maybe that wasn't what you meant by that statement?

Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond
  • Comment on Re^2: Coding style: truth of variable name

Replies are listed 'Best First'.
Re^3: Coding style: truth of variable name
by jcb (Parson) on Apr 20, 2020 at 03:11 UTC

    I had forgotten an important detail. That should be "when the old value is no longer needed and the variable name also describes the new value". This balancing act is to avoid proliferating variable names like $file, $file2, $realfile, and similar problems that I have seen in existing code, including the questioner's example 1B.

    If the role of a variable can change, then (in my view, in Perl) the variable is defined in a scope that is too wide for the code as written. I often reuse the same name for another (similar) purpose later in a sub or script, for example, if iterating over two different sets of files, both foreach loops are likely to use foreach my $filename ..., but the variables are separate lexicals and $filename does not exist outside of those loops.

    Thanks for catching that — the idea that a variable name must describe its contents is something that I tend to assume goes without saying and that the questioner here seems to also tacitly understand, but that is an important detail that a new programmer might not yet know.