Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re^2: Coding style: truth of variable name

by GrandFather (Saint)
on Apr 19, 2020 at 05:37 UTC ( [id://11115776]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11115776]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2024-04-19 15:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found