Come for the quick hacks, stay for the epiphanies. | |
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
The result of this node will most likely be "it depends on the programmer; it is a personal preference", but I would still like to see how others tend to organize their code. The issue I am talking about is where to put the declarations for lexical variables (declared with my()), whether we are talking about file-scoped lexicals (not contained within any block), or lexicals of any block (subroutine, bare block, loop construct, conditional block, etc). As the simple example for this meditation, I will use an example which uses file-scoped lexicals. The first style is to declare all your lexicals at the beginning of the scope in which they are found. The advantage to this style is that you can see at first glance which variables are meant to be used within the scope you've just entered. The disadvantage is that when you finally stuff the variable with data, you can't tell at first glance whether this is the first time data is being assigned to the variable, or if we are redefining it (replacing the current contents with new data). Our example demonstrating this first style:
The second style is to not declare all lexicals at the beginning of the scope in which they are found, but to declare them when they are to first come into existance. The advantage is that you can immediately see where the variable first comes into play in the flow of the program, since the place where it is declared is also the first time it is given contents. The disadvantage is that it is not as easy to determine which variables are used within a particular scope, since we are scattering variable declarations everywhere. The example code rewritten with the second style:
My personal preference tends to lean towards #2 as it is generally easier to follow the program flow. There are times that #1 seems more convenient, such as when you'd like to label each variable with its function. But then there is always POD to do that with if so desired. So I ask of you, the fellow monk, to share your personal preference, as well as any advantages (pros) and disadvantages (cons) you see pertaining to each style. updates: Added a disadvantage to style #2. Modified code for style #1 by making it more equivalent to style #2 -- I moved the $socket declaration to a separate scope containing the while loop. Updated code to reflect tilly's note. I didn't realize I'd declared a hashref and then tried to access a hash. Oops :) In reply to A question of style - declaring lexicals by saskaqueer
|
|