Re: Coding superstitions
by mstone (Deacon) on Jan 08, 2002 at 01:55 UTC
|
That's not superstition. It's called 'defensive programming',
and it's the kind of habit programmers tend to aquire after a
few trips down the razor blade of life. You're adding
information the compiler doesn't need, but so what?
Programming languages aren't for computers anyway.. they're for
humans.
If you want to talk about something we could eliminate, let's
talk about whitespace. The compiler ignores it, except in very
special cases like searching for the closing delimiter of a here
document. Yet programmers wage holy wars about whether to
indent braces like so:
if (&condition) {
&yes;
} else {
&no;
}
or like so:
if (&condition)
{
&yes;
}
else
{
&no;
}
when all the compiler sees is:
if(&condition){&yes;}else{&no;}
And technically, those semicolons aren't necessary either (nor are the braces, now that I think about it). I
always use them, though, because experience has shown that I may
want to put another statement into one of those blocks, and it's
easier to terminate the expression now than to go back and do it
later. I always use a trailing comma in list definitions:
@list = (
'item one',
'item two',
'item three', ## <- unnecessary punctuation
);
for exactly the same reason.
High-level code is for humans. If it wasn't, we'd still be using machine
code. Redundant information, which the compiler ignores, can
still convey information to humans. Conventions like 'always
quote string literals' and 'use meaningful variable names' make
code more useful for humans, even if they don't do anything for
the compiler.
Instead of worrying about whether such things are necessary, ask
yourself how much they cost. So the compiler optimizes out a
few tokens while it's building the syntax tree. Big deal.
It's not worth retraining a habit just to save that dozen clock
cycles or so. And if you personally find the code slightly more
stable or readable, the payoff is worth the cost.
| [reply] [Watch: Dir/Any] [d/l] [select] |
|
...those semicolons aren't necessary either (nor are the braces, now that I think about it).
You're correct about the semicolons, but the braces are necessary. The if-else construct in Perl controls BLOCKs, not statements. Take a look at perldoc:perlsyn. This avoids the dangling-else ambiguity.
Don't confuse this with the if modifier, which comes at the end of statements, not BLOCKs.
I'll let good brother tilly take you to task for (probably inadvertently) passing your current @_ when calling yes and no. ;-)
| [reply] [Watch: Dir/Any] [d/l] [select] |
|
-- edit: adding an interjection: D'oh!
Well spotted..
That's another reason to code defensively. Idioms don't necessarily port between languages, and even silence can mean something in the right place.
FWIW, passing the current @_ is at least syntactically valid, and like so much of Perl, can be used for good or evil at one's own discretion.
| [reply] [Watch: Dir/Any] |
|
There is no need. Brother VSarkiss already did it for me. :-)
| [reply] [Watch: Dir/Any] |
|
@list = (
'item one',
'item two',
'item three', ## <- unnecessary punctuation
);
mrbbking does this...
@list = (
'item one'
,'item two'
,'item three'
);
I picked up this particular habit from some IBM Mainframe DBAs. With the comma on the same line as the thing that comes after it, I can comment out any line of the array assignment and the whole thing is still syntactically valid. I like to keep things as clean as I can.
...in my code anyhow. My office is a pig sty.
...wait a minute... if mstone can get away with an extra trailing comma, then I guess I could comment out the last line of the assigment, and the trailing comma wouldn't cause a problem...
...so this is all in my head... Oh, boy...
| [reply] [Watch: Dir/Any] [d/l] [select] |
|
The trailing comma is good. It means you don't have to
worry about it if you add some new lines to the array.
| [reply] [Watch: Dir/Any] |
|
Unless, of course, someone decides to comment out this line:
@list = (
# 'item one'
,'item two'
,'item three'
);
To be fair, I've never had to comment out the first line of a list in any language. Of course, since you are allowed to have trailing commas, mstone's solution allows you to truly comment out any line. This feature was probably added for this explicit purpose.
| [reply] [Watch: Dir/Any] [d/l] |
Re: Coding superstitions
by YuckFoo (Abbot) on Jan 08, 2002 at 00:14 UTC
|
Ok George,
I confess I always wrap array references: @{$arr}
I also use many unnecessary parens: my ($onevar);
Subroutines that return values always: return $value;
And I avoid using $_.
Thanks for providing the opportunity to confess my
transgressions, interesting subject, but I am still unable
to commit to changing my superstitious ways.
I am curious why you would never use whitespace in a hash
key. Quoting hash keys for consistency seems reasonable to
me. Maybe the real, underlying, superstition is whitspace
in hash keys?
YuckFoo | [reply] [Watch: Dir/Any] |
|
| [reply] [Watch: Dir/Any] [d/l] |
(crazyinsomniac) Re: Coding superstitions
by crazyinsomniac (Prior) on Jan 08, 2002 at 02:47 UTC
|
What do you do at the end of a sub?
sub Hello
{
"I am a sub";
}
I hate that. Nothing particularly wrong with it, it's valid perl, except that I hate it. The following is more to my liking
sub Hello
{
return "No! *I* am a sub.";
}
Hashkeys are a little more forgiving, because how often are you really going to have s p a c e s =>in between, or some such nonsense like others have pointed out, but as with my example above, I'll take being explicit any time over being implicit. I also like to do the following (mainly for visual effect):
$fooBar->Fooz( 'abc' => 1,
'aa0ec' => 221,
'abae' => 12,
'aecadf' => 145,
,)->pack( 'ab' => 11,
'cd' => 22,
,);
| [reply] [Watch: Dir/Any] [d/l] [select] |
|
sub fred {
if ($_[0] == 'ooyah') {
return 1;
} else {
return 0;
}
}
The lecturer insisted that I should take out the else and leave the last return dangling there. I still don't know which I prefer. | [reply] [Watch: Dir/Any] [d/l] |
|
Assuming you don't mind returning 1/undef instead of 1/0 I'd prefer this:
sub fred { $_[0] eq 'ooyah' }
Or, if you want to keep your '0', how about:
sub fred { $_[0] eq 'ooyah' or 0 }
-Blake
| [reply] [Watch: Dir/Any] [d/l] [select] |
|
|
I would replace that entire routine with the ? thingie, as in
sub fred
{
return ( ( $_[0] eq 'ooyah' ) ? 1 : 0 );
}
Gee, I didn't realize until I was replying that you used == and I corrected that to eq. Not bad for some guy who wrote C code forever.
And I disagree with the lecturer about leaving the last return to dangle -- what he/she suggested is obsfucation, and you're not doing yourself any favours with that approach.
--t. alex
"Excellent. Release the hounds." -- Monty Burns.
| [reply] [Watch: Dir/Any] [d/l] [select] |
|
FWIW, I prefer your version, simply because my brain effortlessly translates the else into $_[0] != 'ooyah', so it is immediately clear to me that the block gets executed if and only if $_[0] != 'ooyah'. I think I can understand the prof's desire for the "dangling return", but I also think it would require a few more clock cycles for my brain to look at that and be convinced exactly under which conditions 0 would be returned. (At the very least, I'd have to see the return 1 above to know that the return 0 would never get executed if the if was true -- because the if might just have done some work without actually returning...)
| [reply] [Watch: Dir/Any] [d/l] [select] |
Re: Coding superstitions
by clintp (Curate) on Jan 08, 2002 at 09:30 UTC
|
Superstitions? Hmm. After two books, countless lines of code, and training several hundred people I couldn't think of anything I did out of a fear of the supernatural. After reading the examples given, I gave it a bit more thought and came up with a few specific to Perl programming. (I have all kinds of OTHER superstitions with programming in general...) Distinguishing these from style is a bit tough. If I cross the line, excuse me. These are what I do, YMMV.
Now I break any/all of these when I'm trying to make a point, compress code that's just a side-show, obfuscate, etc..
Update: typo repaired, few late additions | [reply] [Watch: Dir/Any] [d/l] [select] |
|
| [reply] [Watch: Dir/Any] [d/l] |
Re: Coding superstitions
by FoxtrotUniform (Prior) on Jan 08, 2002 at 00:39 UTC
|
I always make explicit dereferences, even with AoAs and
suchlike:
my $bar = $foo->[0]->[1]->{'two'};
(Although, since I think this actually improves my code's
readability, I guess it isn't really a superstition.)
I also use both & and parens when calling
functions, even as I am certain in the knowledge that it
will bite me in the arse sometime in the misty future:
&do_stuff();
I also quote hash keys, for consistency.
--
:wq | [reply] [Watch: Dir/Any] [d/l] [select] |
Re: Coding superstitions
by kwoff (Friar) on Jan 08, 2002 at 05:08 UTC
|
I always quote the key left of an `=>'. It's because
I had bad experiences with earlier perl version with CGI.pm,
where things like $q->popup_menu(-values=>[...]) would
give a warning and it took a long time for me to
figure out that `values' is a perl function. :)
I think the way I figure things out, and it's a bit
cargo-cultish; if I can't find what's causing the problem
but I found something that stops the problem, then in the
back of my mind I avoid doing whatever caused the problem.
It sometimes comes back to bite you though, because you
didn't take the time to figure out WHY there was a problem;
or otherwise, you will end up spending lots of time and
energy approaching a problem a certain way just because
you try to avoid the "dangerous" method.
So, like you say, you have these little superstitions.
Then later you might accidentally discover the real cause,
and those are happy moments of revelation. AHA!
I thought of another example of mine. I single-quote
as much as I can, in the back of my mind thinking that
maybe I'm saving a few cycles by not interpolating a
double-quoted string. :)
I also always use qq{} for writing SQL or HTML strings.
The reason for `qq' is often there are embedded quotes
in HTML, and I forget to change the outside quotes. The
reason for `{}' is in SQL there are often parentheses.
I try to find the most general quotation for all cases
to be consistent.
Also I tend to overuse CODE tags in perlmonks. ;)
| [reply] [Watch: Dir/Any] [d/l] [select] |
Re: Coding superstitions
by Juerd (Abbot) on Jan 08, 2002 at 00:30 UTC
|
| [reply] [Watch: Dir/Any] [d/l] |
Re: Coding superstitions
by jwest (Friar) on Jan 08, 2002 at 03:06 UTC
|
The only superstitious thing that I've noticed in my own code is my apparent inability to, while using DBI, just do something. I always prepare and execute instead.
"What are you preparing? You're always preparing! Just go!" --DH
--jwest
-><- -><- -><- -><- -><-
All things are Perfect
To every last Flaw
And bound in accord
With Eris's Law
- HBT; The Book of Advice, 1:7
| [reply] [Watch: Dir/Any] |
|
Me too. I do prepare, bind, execute, fetch when I could do all this in one call.
Mostly habit, though my rationale is that if something goes wrong, I'll at least know which stage it failed at. (OTOH, the error almost always occurs in the execute stage anyway, so I'm not sure why I bother).
andy.
| [reply] [Watch: Dir/Any] [d/l] [select] |
(ichimunki) Re: Coding superstitions
by ichimunki (Priest) on Jan 08, 2002 at 00:52 UTC
|
Quoting keys distinguishes them from scalars without sigils--and clearly indicates the intent of the programmer. That's the best I can do to defend this practice-- which I will continue to engage in, just as I parenthesize expressions even when it is not necessary to do so for precedence override. | [reply] [Watch: Dir/Any] |
Re: Coding superstitions
by maverick (Curate) on Jan 07, 2002 at 23:48 UTC
|
I always quote mine as well. I think it adds to the readability of the code.
/\/\averick
perl -l -e "eval pack('h*','072796e6470272f2c5f2c5166756279636b672');"
| [reply] [Watch: Dir/Any] |
|
in sort of a related way, I also quote them for readability - mainly because of syntax highlighting in most editors I use will pick up a quoted string, which will highlight the key
| [reply] [Watch: Dir/Any] |
Re: Coding superstitions
by jepri (Parson) on Jan 08, 2002 at 02:00 UTC
|
I quote characters in regexps even when I don't have to. e.g. /\d\d\:\d\d/
Ooops, I meant escape. But you know what I mean, I think. ____________________
Jeremy
I didn't believe in evil until I dated it. | [reply] [Watch: Dir/Any] [d/l] |
|
Hehe. Did anyone else "get it?" :)
| [reply] [Watch: Dir/Any] |
Re: Coding superstitions
by djantzen (Priest) on Jan 08, 2002 at 10:26 UTC
|
Perl appeals to me in much the same way that Kant's moral philosophy appeals to me. It is incumbent upon the coder (or moral agent) to generate the norms by which the code (or behavior) is to be judged, and moreover the individual is solely responsible for adhering to those norms in the absence of an external force (an anal compiler or the police).
I don't love Perl simply because of how few constraints it forces upon the programmer, but because this freedom affords the programmer the opportunity to be self-governing. While you can produce "write-only" Perl by coding inconsistently, the real intellectual satisfaction comes from defining norms that will characterize your code, and then freely acting in accordance with them.
| [reply] [Watch: Dir/Any] |
Re: Coding superstitions
by jonjacobmoon (Pilgrim) on Jan 08, 2002 at 05:29 UTC
|
LOL, good subject. Wish I had some votes left today :)
I think someone mentioned my superstition:
return $value # the keyword is not necessary
Also, I use for for hashes and foreach for arrays. I have no
idea why just a habit I picked up and can't shake. So:
foreach (@array)
and
for (keys %hash)
Always, always, always. I say I do it because it is explicit, but
maybe I am afraid of demons. However, I am not as strong as you
George. I will not give this one up. It is too scary, too
nerve racking. I am just not as brave as you. May your light
shine on us all and clear the way, but for now I need to coward
in the corner :)
I admit it, I am Paco. | [reply] [Watch: Dir/Any] |
Re: Coding superstitions
by buckaduck (Chaplain) on Jan 08, 2002 at 18:12 UTC
|
When using DBI, my database connection handle is always named $dbh. This might not seem too superstitious (after all, if my code looks like the example code it should be easier for others to follow), but I confess that I break into a cold sweat at the very thought of using any other variable name.
Then there's my SQL statement handle, $sth. What if I'm writing a program that uses multiple statement handles? I'm sweating already...
buckaduck | [reply] [Watch: Dir/Any] [d/l] [select] |
|
| [reply] [Watch: Dir/Any] |
Re: Coding superstitions
by Ryszard (Priest) on Jan 08, 2002 at 07:38 UTC
|
I"m a bit of a $retval fan. Whenever one of my (or perls) functions returns something important in the context of my subbie, it gets stored in $retval or @retval and for some strange reason %rethash. Terribly inconsistant I know. Perhaps its because i'm worried it will bring me bad luck if i dont.. ;-)
I also like doing my if..then..elsif..else loops like:
if ($stuff) {
} elsif ($otherstuff) {
} else {
}
| [reply] [Watch: Dir/Any] [d/l] [select] |
|
Heh, I do something similar, except my variable is always called $result, @results, or %results.
| [reply] [Watch: Dir/Any] |
(MeowChow) Re: Coding superstitions
by MeowChow (Vicar) on Jan 08, 2002 at 11:07 UTC
|
I've found that playing alot of golf helped me to relieve myself and my code from such syntactic diarrhea*.
[*] the flip-side of syntactic sugar, perhaps?
MeowChow
s aamecha.s a..a\u$&owag.print | [reply] [Watch: Dir/Any] |
Re: Coding superstitions
by Aristotle (Chancellor) on Jan 08, 2002 at 19:39 UTC
|
The one thing I might call a superstition of mine is how I always seem to try to avoid double quotes - unless I really really need them, I use single quotes. (Which occasionally annoys myself because many inferior editors understand the purpose of double quotes, but do not consider single quotes an equal.)
Rather than "superstitions" though, I would call these "compulsions". Hey, we know that mental health and geniouses generally don't mix :-) | [reply] [Watch: Dir/Any] |
Re: Coding superstitions
by dws (Chancellor) on Jan 09, 2002 at 11:19 UTC
|
I end my modules with
1;
thus missing the opportunity to entertain future generations with my witty sayings and proverbs.
| [reply] [Watch: Dir/Any] [d/l] |
Re: Coding superstitions
by seattlejohn (Deacon) on Jan 15, 2002 at 12:50 UTC
|
Personally, I'd use the term "conventions" rather than "superstitions". (I guess they are superstitions the way there are superstitions about breaking mirrors, which is to say, if I ignore them, I'll fear I'll have seven years of maintenance headaches, er, I mean bad luck.)
Aside from the usual syntactic stuff (how many spaces to indent each level, anyone?), some of mine are:
- Use parens liberally in expressions, to minimize unexpected precedence weirdness. And more importantly, because I find it easier to read code I (or somebody else) has written if I don't have to think through the precedence implications in a complex expression; I can do it, I just don't think it's a good use of my (or anyone else's) time.
- Use descriptive variable names. With a few exceptions my variable names are almost always real word(s) separated by underscores. This way I don't have to worry about whether I called some variable $usraddr or $useraddr; I know it's going to be $user_address. (I also like to think it would be easier to grok for someone who's a non-native English speaker, though that's just speculation.)
- On a similar note, avoid using $i, $j etc. for loop variables. Instead, I use a convention like this:
foreach my $this_address (@address_list) { ... }
- Avoid $_ in most circumstances. I'd rather be explicit about what values I'm using, simply because I find it easier to read later.
- Semicolons after nearly every line (even if they're the only line in an else). Comma after the final element of a hash/array assignment (unless I'm using qw{}).
- use strict, use warnings, test return values of system calls, etc. etc. etc. Any opportunity to let the computer find my errors instead of having to hunt them down myself!
- try to use constant instead of hardcoding any constants in my logic. (I fear I'm far from perfect on this front, though.)
- write POD as I write the code. Write tests before (or at least concurrently with) the code.
- always check CPAN/Perlmonks etc. before going off and writing a "utility" sub -- because somebody has probably already done the work, and quite possibly done it better than I would have.
| [reply] [Watch: Dir/Any] [d/l] [select] |
Re: Coding superstitions
by screamingeagle (Curate) on Jan 09, 2002 at 04:12 UTC
|
My superstitions mirror those of buckaduck i.e. while using DBI, the database handle is always $dbh, statement handles are always $sth (unless I need more than one), and my biggest superstition is :
"Death (or compiler errors ?) comes on swift wings for he who does not use $sql for SQL queries"
i think i need professional help... | [reply] [Watch: Dir/Any] |
Re: Coding superstitions
by Parham (Friar) on Jan 13, 2002 at 04:52 UTC
|
i do this out of habit, and i have no idea why:
if ($value == 1) {
#do something
} #my end braces always go on new lines
i can't help it, i just HAVE to have my }'s on new lines, whereas my {'s can be incorperated into other lines. | [reply] [Watch: Dir/Any] [d/l] |
|
Yes, I've a feeling the Bogey Man wd get me if I ever did something as heinous as:
if (Condition()) {
Do_This();
Do_That();
}
else {Do_The_Other()}
§ George Sherston | [reply] [Watch: Dir/Any] [d/l] |
Re: Coding superstitions
by Amoe (Friar) on Jan 08, 2002 at 23:00 UTC
|
My scripts usually start off fairly regular, then degenerate into trying to do things I know I shouldn't. I always start my scripts like this:
#!/usr/bin/perl -w
use strict;
# useless.pl
# script to demonstrate my perl style
# amoe 2002
use SomeModule;
That's pretty much exactly how all my scripts start off. Even when I'm useing warnings, I put the -w switch in, and use strict somes directly underneath to match my Camel teeshirt :)
--
my one true love | [reply] [Watch: Dir/Any] [d/l] [select] |
Re: Coding superstitions
by goonfest (Sexton) on Jan 09, 2002 at 03:04 UTC
|
{
I always put a comment after the closing bracket of any loop, block, or subroutine etc.
} # end my $.02
"Be proud, be a Goon" | [reply] [Watch: Dir/Any] |
Re: Coding superstitions
by Anonymous Monk on Jan 09, 2002 at 10:35 UTC
|
Although, you could take the approach that superstitions
initially arose out of a need to protect people from some
semi-dangerous endeavour. Hence superstitions like the talk
about "devil dogs" in the German Black Forest, which I'm
sure at one point prevented villagers from wandering out
in the woods at night, and getting mugged or attacked by
wolves or bears. There were no devil dogs, but people
probably occasionally got eaten. Thus, the superstition.
I'd say, keep the quotes. They look nicer, I think, and
keep things cleaner. I'm a real believer in erring on the
side of formality. ;)
Philip P. | [reply] [Watch: Dir/Any] |