Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Coding superstitions

by George_Sherston (Vicar)
on Jan 07, 2002 at 23:40 UTC ( #136904=perlmeditation: print w/ replies, xml ) Need Help??

Do you have any coding superstitions?

I just was about to type $g->{'KeyWords'} and I thought, "this is crazy". Because I *know* I don't need the quotes. But somewhere at the back of my psyche is a half-remembered piece of advice, perhaps from my own anxiety-gland, that it's always a good idea to "get into the habit" in case I should ever have a key with whitespace in it.

Forget that I've never used, and never would use, a hash key with whitespace. All my Perl life I've been using quotes in hash keys. And it's become something I *have* to do... like you went through a phase of not stepping on the cracks between paving stones? Or *always* stepping on the cracks? I keep doing it, knowing that it's pointless, but being irrationally loth to stop.

Well, Perlmonks must stand for casting light into the irrational corners of our code, and so I take this opportunity (A) to renounce my superstition and (B) offer a space for other monks similarly afflicted to come into the light of day.

I, George_Sherston hereby renounce my obsessive urge to place quotes around hash keys even when they don't have whitespace.

George Sherston

Comment on Coding superstitions
Download Code
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');"

      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
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

      Those parens around $onevar with your my create list context, which may or may not be what you want.

      2;0 juerd@ouranos:~$ perl -e'undef christmas' Segmentation fault 2;139 juerd@ouranos:~$

Re: Coding superstitions
by Juerd (Abbot) on Jan 08, 2002 at 00:30 UTC
    I think it's much clearer _without_ the quotes. Any valid bareword will be interpreted as a string, so why not use that? Same goes for => - I don't use quotes if it being a string is obvious.

    Always using quotes might make you forget about words being interpreted as strings, and you might end up using $foo{function} where you meant to use $foo{+function} / $foo{function()}.

    But as _always_, style is what YOU choose. (Just remember some common style issues so others will be able to read your code :)

    2;0 juerd@ouranos:~$ perl -e'undef christmas' Segmentation fault 2;139 juerd@ouranos:~$

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
(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.
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.

      ...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. ;-)

        There is no need. Brother VSarkiss already did it for me. :-)

        -- 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.

      where mstone does this...
      @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...

        The trailing comma is good. It means you don't have to worry about it if you add some new lines to the array.
        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.

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.

      Hehe. Did anyone else "get it?" :)
(crazyinsomniac) Re: Coding superstitions
by crazyinsomniac (Prior) on Jan 08, 2002 at 02:47 UTC
      I know what you mean about returning things. I think it's a deep brainwash from all other languages that says unused expressions are useless. Then there's the case where you can't tell at a glance which line acually does the returning. I like returns.

      On a related (im|ex)plicit note, I argued once when I was at uni about this code:

      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.
        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

        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.

        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...)
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
    
      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.

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. ;)

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.
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 { }
      Heh, I do something similar, except my variable is always called $result, @results, or %results.
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.

    • Trailing commas on lists, especially hashes:
      %foo=( bar => 'baz', poit => 'narf', );
    • Things to the rightleft of => I leave unquoted.
    • I only use & with subroutine calls when I intend to take a coderef (Took YEARS to break that Perl 4 habit...) coupled with always using empty parens on sub-calls I avoid nasty @_ side effects.
    • Identifiers in curlies: never quote them. I know the keywords that'll cause hell.
    • Never ever call a subroutine dump()
    • for is for for(;;) loops, foreach is for iteration over hashes and arrays and such.
    • Use extra curlies when dealing with references, even if I don't necessarily need them. (Along the lines of ${$foo}, but usually more complex).
    • Screw precedence: use parens whenever in the least amount of doubt. If I can't remember it from grade school or a common idiom, then someone else can't either.
    • Declare lexicals with my(). Yes, the parens have context effects. If context is important in a my() declaration, I've broken one of my style rules. :)
    • All statements end in semicolons, whether at the end of a block or not.
    • Explicit returns from subs. Loathe that "falling off" return value.
    • Never ever use the .0 release of any software, including Perl. Unless it's from IBM then never use the .1 release.
    • Subroutine definitions go before the code which calls them. (Pascal habit that stuck around.)
    • grep, split, join, open, close, and system always get parens. map and die do not. (Perl 4 habits)
    • The keyword "unlink" causes me to read, and re-read what I'm typing.
    • The following are all viewed with suspicion and avoided when possible: 3-arg open, locales, unicode, v-strings, overloading, and non-fork threads.
    • Never code towards anything discussed in p5p. When the feature's released -- refrain from using it until +.1 release has gone by.
    • In a regex, I don't backwhack anything that I'm not sure is a metacharacter.
    • Never name a script "test".
    • Loop counter variables always go (in order): $i, $j, $k
    • Avoid implicit $_ except in map, grep, for, or while loops that are very small.
    • Objects in their methods are always $self.
    • Quit in vi is spelled :wq
    • The 1 C-Shell command I trust is "/bin/sh"
    • #! lines always have a blank between them and code. Don't want to crowd the magic.
    • Never ever under almost any circumstances do software updates to production systems on a Friday. Never do updates on any day after 3pm.
    • Never trust the vendor's Perl. Build your own. (exception: Activestate for Win32)
    • When looping over an array, do not insert or remove things from the array. Instead push into a temp array and assign afterwards.
    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

      Things to the right of => I leave unquoted.
      I don't get it... Doesn't => force what's _left_ of it to be interpreted as a string?

      2;0 juerd@ouranos:~$ perl -e'undef christmas' Segmentation fault 2;139 juerd@ouranos:~$

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.

(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
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

      My superstition for databases is... don't use multiple statement handles. If I need more than one, I use different $dbh1, $dbh2. Had funny effects form multiple $sth once, don't wanna repeat. It was probably my fault somewhere, though.

      ____________________
      Jeremy
      I didn't believe in evil until I dated it.

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 :-)
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
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"
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...
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.
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.

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.
      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
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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlmeditation [id://136904]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (7)
As of 2014-12-20 22:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (99 votes), past polls