XP is just a number | |
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
My pet theory is that coding errors and complexity are generally proportional to "total variable scope" of the code in question.
Most of the good advice on coding (avoid global vars, use short methods, avoid objects with too many methods, etc) all acts to reduce the scope of variables (note that object member variables have scope across all methods). Also, adding flags and the like to control loops increases the overall "Sum of variable scopes" in the code (by adding a var). So...my general rule is to declare near/at the point of use. And if that's a long way from the top of the method, then the method is too big. Basically, the more variables you have in scope at any one piece of code, the more combinations of possible states there are, and the harder it is to reason about the code. If a variable isn't in scope, you don't have to expend any precious mental juice wondering if it is related to the bug you are chasing. Perhaps paradoxically, I very often introduce naming vars (e.g. my $badger = foo($some->{lookup}) for reasons of legibility (it acts to remove the need for a comment that the thing I am dealing with is a badger). (It's also driven by the fact that if something fails I have the values handily in vars which will interpolate nicely in an error string without any messing around with string concatenation). But these are often in very short scopes (a single loop or if() branch) - a few lines. I can't work out if this contradicts my rule or if just adding another name for something which is already there (the expression) isn't as harmful (it doesn't multiply the number of states if it never changes). Any thoughts are appreciated. In reply to Re: Naming convention for variables, subroutines, modules, etc.. and variable declaration
by jbert
|
|