Beefy Boxes and Bandwidth Generously Provided by pair Networks Joe
We don't bite newbies here... much
 
PerlMonks  

On Testing and Formatting Code

by jcwren (Prior)
on Oct 03, 2000 at 20:34 UTC ( #35135=perlmeditation: print w/ replies, xml ) Need Help??

I've actually been wondering about this for a while, but a back'n'forth between merlyn and myself in regards to Using formats for 2-columnprinting made me want to pursue this.

Before I post any code, I test it. I do this for two reasons, the primary one being that I am not so good that I can just "wing it". Oh, sure, a print statement or something is easy, but for *anything* that involves a regex, I test it. I have to, or I'll look dumber than usual when it doesn't work. The other reason is a matter of personal pride. I like code that works. I'm embarrased when I write code that doesn't, and frankly, I don't like to feel embarrased. Pride in workmanship kinda thing, I guess (It may not be pretty, but by Dog, it WILL work!)

I am not criticizing people that don't test. Mind you, in the Using formats for 2-columnprinting, merlyn said from the start that it was untested "except in his head" (and I still want to know what version he's running...). I cut'n'pasted the code mostly because it didn't have a 'use strict'. To be honest, I'm very suspect of code that doesn't, and I like to see if it will actually run or not. In this case, a little back and forth determined that our local wizard had forgotten/didn't know that @### combined with ~~ wouldn't work together.

Which brings me to my main point. How many of you that post code actually run it (presuming that it's not disclaimered)? How many of you can't resist reformatting someone elses code when you do post it? (Me, I hate opening braces on the same line as a statement. It's gotta come underneath the verb). I also put a space between a function and it's paranthesis, but no space between the paran, and it's argument.

Looking back through a few posts where I've posted code, I see that I almost always "touch" it to make it more readable, as I define readable. I see a few other people that do that, also. I find this rather amusing, in some ways, like we either are so abhorred by the way it looks we must change it, or we have to "brand" it with our style.

What are your opinions? What do you do? And how many of you try out the code that people post here, whether it's full blown applications, or two line fragments?

--Chris

e-mail jcwren

Comment on On Testing and Formatting Code
Select or Download Code
RE (tilly) 1: On Testing and Formatting Code
by tilly (Archbishop) on Oct 03, 2000 at 20:43 UTC
    Dunno about others, here are my answers.

    I tend to format my own code. I am more likely to worry about someone else's (lack of) error reporting than formatting.

    As for whether I test, well it depends. For short examples I might or might not. If I don't then it either is simple or it is something I can type almost by reflex. Even so I am likely to say, "Untested" from time to time.

    Anything over 10 lines I probably tested quite a bit.

    Anything I had to think about I either disclaim or test or sometimes both.

RE: On Testing and Formatting Code
by Jouke (Curate) on Oct 03, 2000 at 20:50 UTC
    Like you, I always check code samples I post. I'm just not as good as I want to be, so I cannot be sure of myself to write 100% correct code.

    And I don't mind looking foolish. I do mind giving people advice that doesn't work...

    Jouke Visser, Perl 'Adept'
RE: On Testing and Formatting Code
by Adam (Vicar) on Oct 03, 2000 at 20:57 UTC
    When I first started posting code here I tested everything, even simple things like print "hello world\n"; Then I got a little cocky and stopped testing things (it took too long, I would start my post and no one had responded yet, but I would finish testing and my post ended up number 10 or something.) But then I kept feeling guilty. Even with the "untested" tag, I fealt guilty. So now I test almost everything except spuedo-perl-code. Which is to say that I try to make it clear that untested code is untested AND possibly incomplete and I only use it where real code is impractical or unessecary.<sp?>

    As for formating, I'm with you. Open braces go below the function. Plus I wrap long predicates. I vary my wraping on tertiaries based on the length of the sections. I also like indentation. I usually use 4 spaces, but lately I cut that down to 2 in my posts because I don't like horizontal scrolling.

RE: On Testing and Formatting Code
by agoth (Chaplain) on Oct 03, 2000 at 21:42 UTC
    I always test the code I post here, burnt fingers from c.l.p.m, in addition to not liking the embarassment if I do post crud.

    I will usually also reformat peoples code into my style which would in your case painstakingly rearrange all the braces you moved down a line in the first place :-).

    I have occasionally used or at least tried out code from various bits of the site, some of the help has been v useful and some random snippet helped a lot, but I have been known to downvote particularly messy code, NEVER because its not the same style as mine, but because its bad practice. I suspect that may raise a few heckles but it is sporadic, because i hate maintaining Bad Code

RE: On Testing and Formatting Code
by japhy (Canon) on Oct 03, 2000 at 23:23 UTC
    Very rarely do I not test code I post. I know I'm mortal, and code of mine can have errers [sic]. But as for my coding style, I tend to do the following:
    • BLOCKs are started with a brace on the line with the control structure (or function definition), and, except for one-liners, have all EXPRs in them on subsequent lines
      sub NAME { EXPR; EXPR; } sub NAME (PROTO) { EXPR; EXPR; } if (EXPR) { EXPR }
    • Semicolons are optional after one-liners (like above)
    • Closing braces appear on lines by themselves (except for in the case of one-liners (that means I do NOT "hug" my else's)
      if (EXPR) { EXPR } else { EXPR }
    • I use 2-space indents
    • Space between 'if' and '(', and between ')' and '{' (as shown above)
    • No space between function name and '('
      foo(1,2,3); bar({ a => $str, b => $trs, });
    There's a myriad of other things I do, which can of course be divined from my code fragments I display on the site (or my programs you happen to come across).

    $_="goto+F.print+chop;\n=yhpaj";F1:eval
RE: On Testing and Formatting Code
by royalanjr (Chaplain) on Oct 04, 2000 at 00:07 UTC

    I have yet to post any code, but I assure you that I would never think of doing so without testing it!

    I like using parens in my if...then statements, and in other statements where I am testing something

    if ($whatever == anything) then { ...do this stuff... } else { ...do the other stuff... }

    Parens are my friend as far as I am concerned. It just really helps me to keep things in order a lot of the time. Never underestimate those little guys *grin*

    Roy Alan

RE: On Testing and Formatting Code
by turnstep (Parson) on Oct 04, 2000 at 01:20 UTC

    I always, always, always, always test my code before posting it. I think that any responsible monk should do the same, no matter how good you think you are (and I have seen other Saints post mistakes). Not testing your code might allow you to post it faster, which some see as an advantage because some days, to be honest, this place is more of a "who can answer it first" rather than "who can answer it best." Remember that higher experience indicates not only (hopefully) a good grasp of Perl, but more importantly, it indicates that someone has actual Free Time to spend on the site answering questions. Ok, I've diverged a bit. Perhaps this is the topic of another discussion. For the record, I usually reformat (there are notable exceptions*) and my guidelines are pretty much the same as japhy's above.

    *Yes, it's the Worst Node Ever. Have *you* voted it down yet? :)

RE: On Testing and Formatting Code
by takshaka (Friar) on Oct 04, 2000 at 01:58 UTC
    Except for very short bits of code (obvious stuff that we've all used hundreds of times), I test everything before posting and paste it straight from emacs. When something is untested or may not work as advertized, I'll say so.

    I format pretty much like japhy, mostly straight out of perlstyle except for a few idiosyncracies. But I try to respect other people's coding styles--even when they are wrong, wrong, wrong; I only reformat when something is so godawfully written that I have trouble following it. I may unconsciously do it at other times, but I try not to.

    As for testing other people's code, I only do that if it looks broken or really cool, or if I want a benchmark.

RE: On Testing and Formatting Code
by TStanley (Canon) on Oct 04, 2000 at 07:16 UTC
    IMHO there is no such thing as too much testing. I use perl
    on an irregular basis, and quite frankly, I still have
    a lot to learn about this amazing language. So any code
    that I write, I double and triple check it, to make sure
    that it works.

    TStanley
    There can be only one!
(zdog) RE: Test and Format Code!!
by zdog (Priest) on Oct 04, 2000 at 09:00 UTC
    This is a very good topic that you bring up. Often I wonder how many people don't test code before they run it... As for me, I test everything, and I mean everything. Some people, like you, are proven good coders and if they make a mistake here or there, people usually don't think much of it. But I am not a good coder, and I don't pretend to be, so posting something wrong would not only make me look silly or dumb, but it would make me look stupid. If the code is something more complex, I make sure that the code not only runs, but it does what I need it to do. (I feel that that is a very important distinction, code that runs, and code that works.) As far as posting regexes, well, I don't, too dangerous. :-)

    Secondly, I love reformatting code. I love code that looks good and I love to make code look good, good for me, that is. You mentioned putting braces underneath a statement, well, I would undo that, but again, it's a matter of opinion. I also like aligned comments and bulky or long lines (looks more advanced that way, also is less wasteful :-)). I also do the exact opposite as far as your funtion, paren relationship goes, but an argument over that should be somewhere else. The point is, well formatted code is important to me (it is also the easiest to do for me :-)).

    Well, that's my opinion.

    Zenon Zabinski | zdog | zdog7@hotmail.com

RE: On Testing and Formatting Code
by extremely (Priest) on Oct 04, 2000 at 13:31 UTC
    It is a rare thing when I don't test code I post, usually only trivial stuff gets past the "I should test that" filter.

    More importantly, I try and benchmark things against other answers. I always wanna know why/how things work so one day when it does matter that I did it the fast way, my instincts will lead me down the mostly-right path =)

    As to formatting, I like compressed code, so I tend to hang the open braces on the main line and indent body only. I ALWAYS use tabs IRL and tend to have my vim set to 3space tabs.

    Spacing brackets and parens is becoming a habit as well, I pad inside and out of brackets, braces, and parens that block code, enclose arguments, or create arrays/lists. Never spaces on array brackets or hash keys. Space on both sides of assignments and math is generally a must, excepting a few degenerate cases like $a+0 and the like.

    Vertical whitespace is for separating logical blocks of code, especially in long linear sections.

    --
    $you = new YOU;
    honk() if $you->love(perl)

      Were you working closely with me I would be unhappy about the non-standard tab-stop.

      I leave editors at the default 8 spaces. Your code would probably not display nicely for me in 80 columns and I would request that you change your settings to make sure your tabs become spaces in the file. I don't care what happens on your screen when you hit tab. I do care that the output is readable for me, prints properly, etc. And since others use editors with 8-space tab-stops, I am not going to be sympathetic to changing to match what you are doing...

      Oh, and the first time you open and touch some Python code? You will turn it into a complete and utter mess! Seriously, Python uses indenting for its logical structure, and non-standard tabstops can result in your not being able to read it, and then it's not being able to read it either after you make a trivial edit and spaces are converted to tabs (or vica versa)!

        No, you read that wrong. My editor leaves tabs as tabs. In code I write for work I NEVER EVER use spaces. I set my EDITOR to use 3 space representation. Most people here leave theirs set to 4 or 8. But they are free to use what ever they like. My Python code works great. Every tab is a level and it prints beautifully, compact and clean. Better still, since it's all tabs, any goofus who wants can smash tabs to 8 spaces and further fsck it up at will.

        The porpoise of the odd fish "tab" is to indent, with flexibility of representation. That it is abused into spacing to ($col + 8 - ($col % 8)) is just a shame.

        Rewriting you last paragraph (no offence here I'm trying not to devolve into ad hominem attacks) :
        Oh, and the first time you open and touch some Fortran code? You will turn it into a complete and utter mess! Seriously, Fortran uses indenting for its logical structure, and non-standard tabstops can result in your not being able to compile it, and then it's not being able to read it either after you make a trivial edit and spaces are converted to tabs (or vise-versa)!

        So what? We weren't talking python here and why should I care if my Perl habits might cause me trouble editing Python? You don't see me decrying your Perl habits inflicting woe upon your writing paragraphs of off topic-ness. Why not? Because you don't blindly type a "$" or "@" in front of every noun and tell people to precede their documents with "use grammar;". I, and you clearly, are able to keep more than one way of formatting and describing information straight. Please don't mis-read what I say " I ALWAYS use tabs IRL and tend to have my vim set to 3space tabs." and then call me ignorant to my face.

        Sorry if this came off too heated tilly. I didn't mean it to insult you but who are you to chide me? Especially with the specious "wait till you hit Python" argument.

        --
        $you = new YOU;
        honk() if $you->love(perl)

RE: On Testing and Formatting Code
by clemburg (Curate) on Oct 04, 2000 at 16:57 UTC

    1. I always test code I post (habit).
    2. I try to fit in with the coding style of the code I am changing - it increases the chance that the person writing the original code will understand what I did.

    Christian Lemburg
    Brainbench MVP for Perl
    http://www.brainbench.com

RE: On Testing and Formatting Code
by PsychoSpunk (Hermit) on Oct 04, 2000 at 20:37 UTC
    I tend to disclaim whether the code is known to be good or not. I've only posted small tidbits, and usually from a working program, in order to get around to my problem (like Referents Anonymous.) where I will write what I'm attempting to do.

    But I tend not to write code in the majority of my posts, instead relying on the fact that theory translates better than code for problems we may all be facing at some point.

    As for the braces problem, for verbs, the braces start on the line below, but subs keep the braces on the same row. It's actually got a method to the madness. In the case of a verb, the code may get executed, and thusly, I don't want to be led into the code by my eyes while I'm reading over it. In the case of a sub (although it has a verb name), once I get to a sub, it will be executed, and so I do want my eyes led into the code. It's a case of "I might" vs. "I will".

    ALL HAIL BRAK!!!

RE: On Testing and Formatting Code
by swiftone (Curate) on Oct 04, 2000 at 21:56 UTC
    As a general rule, I test regexes only (haven't posted large code blocks for the most part). (I will occasionally post untested code and then update it once I've had a chance to test it.)

    I do my best to follow perlstyle to the letter, even if it's not my instinctive style, because I think SOME standards are better than none. Unless it is totally illegible, I'll leave other people's code alone.

    I never test others' code here, unless I'm suspicious. I'll always work to understand how code works before putting it into my work, so if there are errors, I'll find them (or just not understand and ask for help)

RE: On Testing and Formatting Code
by chromatic (Archbishop) on Oct 05, 2000 at 03:59 UTC
    I test most of my code. If i don't test it, I label it as 'untested'.

    If I'm just demonstrating a technique I've used before, I probably won't test it. If it's a regex or corrected code (beyond stuff I really know), I'll test it.

    There's no hard and fast rule... but demonstrating a general technique can get by with pseudo-working code.

RE: On Testing and Formatting Code
by adamsj (Hermit) on Oct 08, 2000 at 01:56 UTC
    I always test unless I'm certain something will work--even then, I usually test. ("I am only an egg.")

    I almost always reformat code if I touch it at all--ever read Stranger in a Strange Land? My most quoted line from that book is Jubal Harshaw's "After an editor pees in it, he likes the flavor better" (or words to that effect).

    I sometimes try out code--usually fragments. (I don't have an SiaSL quote to go with this one--sorry.)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (7)
As of 2014-04-18 00:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (460 votes), past polls