Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Commonly accepted style guide?

by dragonchild (Archbishop)
on Sep 25, 2005 at 03:14 UTC ( #494842=perlmeditation: print w/ replies, xml ) Need Help??

In Re^2: beginner Rpg/Mud, I criticized the code for PerlMUD as being buggy and having about 300 style violations. In a /msg discussion that ensued, sauoq argued that there is no community style guide, outside of what the perl interpreter will accept as legal. As my update to Re^2: beginner Rpg/Mud states, I agree with him, on the face.

However, I would like to put forward that there are commonly accepted standards, usually promulgated by the elders of the community at large (like merlyn, TheDamian, and others) in various media (like books), that set the expectations of the average Perl programmer. These standards are closely related to, but not identical to, the standards put together by the venerable K&R for C. These standards are also those which McConnell (in Code Complete) and others in numerous books on programming theory (such as the Gang of Four in the Patterns book) have used in their examples. By constant repetition, I would argue that these standards-in-print should be considered the de-facto community style guide, to be used as the basis for specific organizational style guides.

My argument is, in my mind, bolstered by my experiences as both a Perl consultant and as a CPAN author/contributor. I have worked nearly exclusively in Perl at 9 different companies in 6 different states over the past 10 years. In addition, I have 4 distributions on CPAN, have contributed patches to at least 2 dozen others, and have read the source for dozens more. All of that code over all those years from all those authors has, for the most part, looked very similar. They have been so similar that I have both come to expect certain ways of writing things from well-written Perl code. In addition, I use the existence of other modes of expression as red-flags that I have to examine this piece of code more closely for the existence of bugs and/or design flaws.

I'm wondering:

  • Do you feel the same way?
  • What items do you unconciously look for as signals that what you're reading merits a closer look?
  • Are there items that make you feel more comfortable with the code?
  • Do you feel you can rate the experience level of the author by how the code looks, both in Perl and programming in general?
  • Has your style changed as you have improved as a programmer, both in Perl and in general? If so, how?
  • Do you think that the style of a piece of code can contribute to its maintainability?
Please note that I'm not proposing the creation of a community style guide (though I wouldn't be opposed to one). I'm also not talking about indentation levels, camelCase, or cuddled elses. I'm talking about more fundamental things, like
  • Do you indent at all? If so, how?
  • How do you write data structures? How do you access them?
  • How do you structure your logic?
  • How do you call your subroutines?
  • What kind of naming conventions do you use?
  • What do you consider worth putting into a subroutine? How do you structure them?

My criteria for good software:
  1. Does it work?
  2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?

Comment on Commonly accepted style guide?
Re: Commonly accepted style guide?
by pg (Canon) on Sep 25, 2005 at 04:30 UTC
    "Do you feel you can rate the experience level of the author by how the code looks, both in Perl and programming in general?"

    Tough question... Take Perl as one example, Perl can easily attracts people to play little tricks. If I see a piece of code that plays tricks here and there, am I facing a experienced Perl programmer? Maybe, but not a programmer with good style. Personally I don't view people with bad style as experienced programmer.

Re: Commonly accepted style guide?
by sauoq (Abbot) on Sep 25, 2005 at 04:42 UTC

    Just to fill in the background a bit... our discussion, or at least my part of it, centered entirely around the word "violation." A style "violation" assumes some sort of accepted coding standard and there can be no violation in the absence of one.¹ Even a "community style guide" would not resolve the issue as one would have to accept that guide before we could say he had any "style violations"

    I agree with dragonchild's assessment of the PerlMUD code, by the way. I'd just label it "exceedingly poor style" rather than make claims about "violations". Perhaps I have an issue with authority. :-)

    In any case, I do believe there are certain de-facto standards that exist for Perl code among those who aren't writing Perl in a vacuum. This has come up here before. (I'll post a node link here later. later: Here it is: My coding guidelines. Those are Abigail-II's coding guidelines, btw. Not mine.) And Best Practices seems to address this pretty head-on. For those who use it, Perltidy addresses at least some style issues in a more hands-on way.

    [1] I make one exception: inconsistency is always a style violation. If it isn't consistent, it isn't a "style" at all.

    -sauoq
    "My two cents aren't worth a dime.";
    

      A recent module, Perl::Critic, has a nice command line interface ( perlcritic) that tells you which of Conway's "Perl Best Practices" your code might be violating.

      For example:

      $ perlcritic `perldoc -l Time::HiRes` Package variable declared or used at line 4, column 1. See pages 73,75 + of PBP. Deprecated 'require' statement used at line 6, column 1. Use 'use' pra +gma instead Deprecated 'require' statement used at line 7, column 1. Use 'use' pra +gma instead Code before warnings are enabled at line 9, column 1. See page 431 of +PBP. String form of 'eval' at line 20, column 12. See page 161 of PBP. Useless interpolation of literal string at line 25, column 9. See page + 51 of PBP. Postfix control 'if' used at line 25, column 46. See pages 93,94 of PB +P. Postfix control 'unless' used at line 42, column 27. See pages 96,97 o +f PBP. Builtin function called with parens at line 42, column 34. See page 13 + of PBP.

      If you aren't brave, don't do that with CGI. :)

        Just from that output, that looks like quite possibly the most useless piece of code ever written. Require is now deprecated? We can't call builtins with parentheses? Postfix ifs are bad? Since when?!
Re: Commonly accepted style guide?
by Anonymous Monk on Sep 25, 2005 at 05:08 UTC

    Perl itself is a style pig, simply take a look at the fat perlvar.

Re: Commonly accepted style guide?
by Anonymous Monk on Sep 25, 2005 at 05:10 UTC

    Style for a language can not even define properties as private?

Re: Commonly accepted style guide?
by Tanktalus (Canon) on Sep 25, 2005 at 05:20 UTC

    Style being de-facto standards: yes, wholeheartedly. As for "community standards", I'll leave that as a philosophical question on what "community" is ;-)

    Items to pay attention to:

    • Use of & in function calls.
    • Any failure to use strict and warnings, or any use of no strict without a comment explaining why this is necessary.
    • A for/foreach loop whose sole job is to push values (whether they're the loop variable or converted from it) onto an array - cf. @array = map {...} @list;
    • Using backticks in void context. Or any other construct that returns a list, e.g., map.

    More comfortable: Using lots of modules. It means that the author understands his/her tools, and is using stable modules to do work rather than reinventing bugs in new wheels.

    Experience level: If you are willing to agree that experience level and amount of experience are not tightly bound, sure. I know a number of people who have been writing perl for longer than I've been in the field who I'd say are extremely low-leveled. They just never progressed past perl4-style programming. So, to a point, yes - bad style shows a lack of time writing and maintaining code - many good styles should be obvious once you have to maintain code. Anyone with a modicum of experience should have learned good style, whether exposed to it from others or not. From the other direction, I do think it's completely possible for someone with no experience in writing code to quickly be high-level programmers if they are good at learning and applying what others before them have encountered. I think the bottom line to the question is relating to how comfortable you feel in maintaining someone else's code - and that really does come down to style. Mostly.

    Yes, my style has changed. I'm not sure it's always an improvement ;-). How it has changed? As I learn more about perl idioms, I tend to use them. They make my programs more robust as these are general-purpose ideas that have been around for a long time, well-tested, and probably even have optimisations put into the perl interpreter to help speed them up.

    Your final question: I think style and maintainability are nearly interchangeable terms. They are tightly intertwined. And, in my personal arrogance ;-), I think that's why I'm an advanced programmer.

      Any failure to use strict and warnings, or any use of no strict without a comment explaining why this is necessary.

      Using 'no strict' without a comment is something you pay attention to, and I presume you flag it negatively? I disagree. I consider commenting the obvious as a sign of an immature or insecure coder. Commenting the obvious includes the classical:

      i++; /* Increment i */
      but doesn't stop with:
      { no strict 'refs'; *{$caller} = &{$something}; }
      or
      my @list = do {no warnings; qw /foo #bar baz,/};

      Using backticks in void context. Or any other construct that returns a list, e.g., map

      Nothing returns a list in void context. Lists are only returned in list context. And programmers who think that 'map' in void context creates a list internally are showing signs of not keeping up with modern Perl development. ;-).

Re: Commonly accepted style guide?
by chester (Hermit) on Sep 25, 2005 at 06:11 UTC
    "Are there items that make you feel more comfortable with the code?"

    There are things that definitely make me feel more uncomfortable. For example, cramming a dozen functions onto one line in some kind of clever but completely unreadable tangled chain. Of this sort:

    @_ = join "\n", map {/$complicated_regex/} split '', join ',', reverse sort map {lc} map {do_backflips($_)} keys %{ $var->{$something} };

    On the same token, massive amounts of referencing and dereferencing:

    $data_ref = [ @{ @{ $ref->{ $sub->(\%hash, {key=>[@_[0..4]]}) }}[0] }[1..3] ];

    I don't even know if that line is valid Perl, but I've seen that kind of thing given as a response here at PM sometimes. It might save you from allocating variables to store temporary references, and maybe you'll save 12 bytes of RAM and 15 nanoseconds of compute time, but I don't think it's worth the pain it causes my brain to try to parse it.

    Isn't there some kind of natural limit to the amount of things a person can hold in short-term memory? One-liners are clever and fun, but probably don't belong in code that anyone else ever needs to read.

    "Do you feel you can rate the experience level of the author by how the code looks, both in Perl and programming in general?"

    When code is written with heavy use of Perl idioms, I tend to think the person is more experienced.

    I agree with pg that this isn't always a good thing. Unless you're the only person who needs to read your code, it's not too useful to be really good at speaking a language no one else can understand. Some idioms, like $data = do {local $/; <FILE> }; or something, are useful and straightforward and simple enough that one could reasonably expect a "Perl programmer" to know what it means. More complex or obscure or inventive idioms are probably not a good thing (unless you can convince everyone else to use them. How's that for some logic. :) ).

    "Has your style changed as you have improved as a programmer, both in Perl and in general? If so, how?"

    The better I get at programming, the less work I (need to) do. I use more and more of the CPAN to do the dirty work for example. Or learn to take something I wrote and stick it somewhere I can reuse it. And learning to write clean code means I'm less likely to have to fix something or re-write something in the future.

    I also find my code being longer, in the sense that I write more verbose code for the sake of making it easier to read and edit later. This is a good kind of longer. More typing in the short-term, less work in the long-term.

    Lots of other things. There are so many ways to do things (especially in Perl) that you can't help but change the way you write code over time.

    "Do you think that the style of a piece of code can contribute to its maintainability?"
    Style is pretty much all that contributes to something's maintainability.
      cramming a dozen functions onto one line in some kind of clever but completely unreadable tangled chain

      I'm not quite sure I'm in agreement with this one. It's not tangled, it flows from right-to-left. It's such a nice idiom that Perl 6 introduces the ==> operator, in order to reverse the flow. It will go from left to right, and I suspect the result will be much more readable.

      And if you think it's a tangle, the style question at hand is that of the Correct Use of Whitespace. A well-indented chain of functions should be eminently readable.

      massive amounts of referencing and dereferencing

      No disagreement with this one. Programmers in C used to create intermediate typedefs in order to get around this problem (like a "pointer to array of functions returning an int with parameters of a pointer to a void function taking an int and an array of characters").

      While this exact problem doesn't arise with Perl, the problem of decoding what a massive dereferencing statement is doing can be pretty brain-melting.

      • another intruder with the mooring in the heart of the Perl

        <RANT>Considering how twisted the syntax of C types gets as soon as pointers, functions and arrays are involved using typedefs is pure self-defense. Hey, what's the syntactical difference between the declaration of a function returning a pointer to int and a pointer to function returning int? Seems to me someone failed to envision the posibility of types more complex than an array to foo or pointer to foo.</RANT>

        Jenda
        XML sucks. Badly. SOAP on the other hand is the most powerfull vacuum pump ever invented.

        I agree that whitespace can be a big difference. That's actually my problem; if that was broken up into lines, I'd say it was mostly OK. If you get this:

        @_ = join "\n", map {/$complicated_regex/} split '', join ',', reverse sort map {lc} map {do_backflips($_)} keys %{ $var->{$something} } ;

        Imagine some more assignments on the left and some more semicolons on the right and it's pretty much equivalent to reading any other code (except that you have to read it backwards).

        I agree that even my first example as it stands isn't nearly as confusing as my second with the referencing. At least the flow of the first is linear; nesting things is much worse.

Re: Commonly accepted style guide?
by sauoq (Abbot) on Sep 25, 2005 at 07:21 UTC
    • What items do you unconciously look for as signals that what you're reading merits a closer look?

    Firstly and most commonly: poor function names. Secondly and almost as common: poor variable names. Thirdly: poorly written comments.

    If I see @n[$i] I get very worried.

    • Are there items that make you feel more comfortable with the code?

    Good function names, variable names, and comments.

    • Do you feel you can rate the experience level of the author by how the code looks, both in Perl and programming in general?

    Generally and to some extent, yes. But there are lots of exceptions. There are some capable but entirely self-taught developers who have peculiar styles and I've seen some really lousy Perl code written by very good C programmers. At the extreme lower end of the scale, though, it's usually easy to judge experience, at least with a particular language.

    • Has your style changed as you have improved as a programmer, both in Perl and in general? If so, how?

    Sure. How? That's a big question. I guess a concise way to put it is that my code has gotten more expressive. By which I mean that my intentions are, I think, more transparent to the reader. Another shorter way to put it is that my code makes more sense these days... ;-)

    • Do you think that the style of a piece of code can contribute to its maintainability?

    Of course.

    -sauoq
    "My two cents aren't worth a dime.";
    

      If I see @n[$i] I get very worried.

      I don't. It's about time we got rid of that warning. It's going to be the right syntax in perl6, it's doing the right thing in perl5, and considering that:

      @n[$i,$j,$k,$l] @n[$i,$j,$k] @n[$i,$j]
      return 4, 3, and 2 element slices - the use of @n[$i] isn't unnatural at all. Its a one element slice. And what does a slice in scalar context return? It's last element. Which, obviously, is $n[$i].

      So, I think in this case that Perl should act perlish, and shut up and DWIM (which it is doing already). And not whine and pretent to be Java or Python.

        I don't.

        Perhaps you should. Here's one example (paraphrased from real life) of how it can get ugly...

        #!/usr/bin/perl $\=$/; @n[0] = localtime; $n[1] = localtime; print for @n;

        -sauoq
        "My two cents aren't worth a dime.";
        
Re: Commonly accepted style guide?
by Juerd (Abbot) on Sep 25, 2005 at 13:22 UTC

    Do you feel the same way?

    Partly. There is a need for commonly understood Perl code, so that not everything winds up obfuscated and unreadable, but there should also be recognition of the simple fact style is mostly personal. I may not like the way you use your whitespace, but if it doesn't affect readability, you usually don't hear me complain.

    Of course, and I'll note this before anyone else does, I usually do think certain styles hinder readability. :)

    I'm a bit of a hypocrit in this area. At the same time I find that everyone is allowed their own style, AND I think there are some important things that should be standard and followed by all Perl programmers.

    What items do you unconciously look for as signals that what you're reading merits a closer look?

    The usual red style flags:

    • spaghetti code
    • lack of indentation
    • lack of module use
    • lack of strict
    • declaration lists (e.g. my ($foo, $bar, $baz, $quux); or my $foo; my $bar; my $baz; my $quux;)
    • c-style foreach index (e.g. for (my $i = 0; $i <= $#array; $i++) { ... })
    • lack of encoding/escaping
    • everythingcrammedtogether
    • overuse of \-escapes (e.g. in regexes, /\>/)
    • stupid variable names (e.g. $data)
    • comments translating Perl to English (e.g. $i++; # increment $i)
    • subs called with &foo()
    • subs called with &foo without comment like "re-use @_"
    • prototypes, especially when meaningless (e.g. sub new ($$$) { ... bless ... })
    • symbolic refs where arrays|hashes could be used

    Are there items that make you feel more comfortable with the code?

    Certainly. One might call them green flags.

    • strict, warnings
    • sane and short variable names
    • consistent indentation in the style I like
    • use of certain modules (e.g. Fatal.pm and templating modules)
    • smart and useful comments
    • -T

    Do you feel you can rate the experience level of the author by how the code looks, both in Perl and programming in general?

    Partly. If it's inconsistent, the author is inexperienced. If it's consistent, the author may be experienced. Do note that experience and skill are not the same thing and not always closely related.

    Has your style changed as you have improved as a programmer, both in Perl and in general? If so, how?

    Yes; it became more consistent and readable (mostly because of the consistency, though). I use more language features than I did before.

    Do you think that the style of a piece of code can contribute to its maintainability?

    Yes!

    Do you indent at all? If so, how?

    Yes. If something is continued on a new line, I indent according to balanced brackets, like {}, () or []. The opening bracket is on the same line as the thing before it, the contents are indented, the closing bracket is in the same column as the last lesser-indented line, or explained differently: no longer indented.

    Sometimes I indent long lines without using parens. Then it's after an operator, or after the name of the function I'm calling.

    I indent complex ?:-structures. The first line has the condition and is not indented. The rest is indented, with ? or : each beginning a new line.

    Indents are ALWAYS 4 spaces. There are no half-indents, outdents or tabs. I do not consider initial whitespace used for lining up vertically indentation.

    How do you structure your logic?

    However the logic makes most sense to me.

    How do you call your subroutines?

    Usually parenless on statement level (in void context), but often with parens if it's spread over multiple lines (because parens make indenting clear) or if it's part of a larger expression.

    What kind of naming conventions do you use?

    Variables are named after their contents, simple, and do not indicate type. Arrays and hashes are usually in plural. Names are all lowercase, except module names. Words are together, and when separated (very rare), with underscore. Sub names indicate return value (like int, not like hex) and when they do something, they're imperative and when used with an object, they're verb-object (like readline and encode_entities), not object-verb (like uri_escape).

    What do you consider worth putting into a subroutine?

    Everything that's called more than once or does a specific thing. In general: when it can be named without using generics.

    How do you structure them?

    Depends wildly on what they do.

    Juerd # { site => 'juerd.nl', plp_site => 'plp.juerd.nl', do_not_use => 'spamtrap' }

Re: Commonly accepted style guide?
by wazoox (Prior) on Sep 25, 2005 at 14:03 UTC
    There actually is a very official perl style guideline :perldoc perlstyle. It's quite broad, but it makes a nice standard to build upon.
Re: Commonly accepted style guide?
by jpeg (Chaplain) on Sep 25, 2005 at 18:57 UTC
    If I see someone criticizing style in response to a question about the content of the code, I usually assume the respondent is an ass. For whatever reason, that person is making someone jump through hoops to be helped or thinks style is just as important as functionality. Even worse, the respondent has forgotten that TMTOWTDI.

    I think contributing here at perlmonks or other forums is like being a teacher: we're trying to promote learning. The best way to get someone to learn is to engage them in the subject matter. The best way to turn a student off and completely disengage their minds is to give them a lot of facts and rules for rote memorization.

    Answering questions is also like being a maintenance programer. Our job is to adapt and work within an established framework, not rewrite as we see fit.

    Promote readability and understanding of the language. Solve problems with content of a newbie's code, not the style. Once the newbie becomes a hacker, they'll develop the desire to write using clean style on their own.

    --
    jpg
      There might be some 'extra' radio boxes when submiting some code block that would dissable the use of perltidy to reformat every piece of code submited. Or other options to add to perltidy: do not erase comments, etc. All these would preserve certain PM standard style for every code displayed, wouldn't it?
      ...that person ... thinks style is just as important as functionality.

      I think it is, if you have to maintain code. Certainly working code is important. If it's truly a one-off and you never have to maintain it, style isn't as important as completeness and correctness.

      I think it's a bad habit to write unstylish code even for one-offs, though. I've maintained too many programs that managed to stick around far longer than anyone expected. I've also seen too many buggy sections of code written poorly because someone rushed to make a fix. If you don't have the discipline to write code well even when you're experimenting, do you have the discipline to write code well when you're under pressure?

      Even worse, the respondent has forgotten that TMTOWTDI.

      That's a silly argument. It's stupid to pound nails in with a rock (or your forehead) when there's a perfectly serviceable hammer right next to you.

      You don't have to take style advice, but it's free and it comes from a community that has, as a whole, orders of magniture more experience designing, developing, and maintaining programs than any one poster. I think failing to consider that advice, because Perl allows you to solve problems in many ways, is a mistake.

        Your post is very good and matches the way I feel very closely. ++

        If it's truly a one-off and you never have to maintain it, style isn't as important as completeness and correctness.

        Agreed. But I would like to add that I don't expect code I get to see to be a one-offs, and criticize all style flaws in code I'm asked to comment on.

        In other words: one better not bothers others with one-offs.

        Juerd # { site => 'juerd.nl', plp_site => 'plp.juerd.nl', do_not_use => 'spamtrap' }

        [TMTOWTDI]'s a silly argument. It's stupid to pound nails in with a rock (or your forehead) when there's a perfectly serviceable hammer right next to you.

        But who is to say which way is the forehead, and which is the hammer? More important is that the nail achieves its final destination. Maintainability is secondary to that. The tool used for the job is a far-distant third, or possibly even fourth (Forth?).

Re: Commonly accepted style guide?
by perrin (Chancellor) on Sep 25, 2005 at 20:11 UTC
    Style matters, because code that other people can't easily read is bad code. My definition of good formatting style is the one commonly seen in the canonical reference books like Programming Perl. This is easy to get by running perltidy with default options.
Re: Commonly accepted style guide?
by bprew (Monk) on Sep 26, 2005 at 21:46 UTC

    Note: Most of my thoughts have extended from a main thought, which is: What are you trying to do by writing code, Perl or otherwise, and what kind of activity would you consider writing code to be?

    In Knuth's Turing Award acceptance speech, he discusses computer programmer as an art. In his speech he discusses how computer programmer is closer to the same kind of process an artist goes through. He is careful to define art as more of the artisan style of art, where "technique" and "skill" are used, rather then more abstract, subjective concepts more closely related to "fine arts".

    Knuth also views code akin to "Works of Art", where it is more difficult to simply look at a program and grade it based on a standard. In his mind, writing code is similar to composing music, so what one person finds repulsive, another might find very beautiful.

    In this case, I would argue that there is no one "correct" way to write code. When I look at your code, I might find it quite ugly or obtuse, but as the writer, I would anticipate it made sense to you. Also, there are many small design decisions that get made that cannot be understood just by seeing the code. And, the code may be solving different small problems to get to the large solution then a corresponding program.

    As an example, I am working on some code that has a low-technical userbase. Given this, I have shied away from the "normal" install method and "normal" Perl modules, choosing rather to hand-code most of the functionality I need. I realize this is re-inventing the wheel, but my goal is not code-reuse, but rather a low barrier of entry for the user. So, if all they have to do is download the program, and start Perl, rather then trying to install 3-4 CPAN modules, then I am willing to spend the time re-writing the code. Plus, the additional coding work means that my code is tailored to what I want to do, and I have a good understanding of everything that is going on inside the system, and, in most cases, I am able to have an overall faster system because my modules are tailor-made to solve my problems.

    This may not be the most generic solution, or the solution that many others would follow, but in my case I have thought about the decisions I am making, and I chose one of many available paths.

    All of this is not to say that when I look at a piece of code, that I do not have my own opinions about the style or the conventions. Every construct has trade-offs, and while there are some that I would consider obvious, not everyone agrees with me.

    When I code-review code for work, I am quick to point out things that I see as "unclear", or "bad style". Given that our software is fairly mature at this point, an implicit style has arisen, but I would argue that it is a single "body of work", rather then multiple separate bodies, so consistency within the single body is reasonable.

    Also, here are my answers to your specific questions:

    * What items do you unconsciously look for as signals that what you're reading merits a closer look?

    Usually anything I don't understand merits a closer look... if only for my own knowledge, or confirmation of my suspicions.

    * Are there items that make you feel more comfortable with the code?

    When its closer to my style :). Honestly, when the code more closely follows how I would have solved the problem, it makes me feel more comfortable. Of course, this means that just because I am comfortable with the code does not mean that it is a good solution to the problem.

    * Has your style changed as you have improved as a programmer, both in Perl and in general? If so, how?

    Definitely. I try to abstract things sooner, to try and make them more ubiquitous. I use more references to functions and closures. As I learn more, my "toolkit" gets bigger, and I find myself calling a wider variety of tools I become comfortable using them. For someone who is not comfortable with the same set of tools I am, I am sure my code could be constructed as confusing, or poor style, but when I knew very little Perl I would have considered most code confusing, and if pressed, in bad style, but only because I myself could not understand what was happening.

    * Do you think that the style of a piece of code can contribute to its maintainability?

    Yes, the closer you get to the lowest common denominator, the more people you allow to maintain the code. However, often times difficult problems can be expressed more cleanly with code that is more advanced, but it does reduce the number of people that can maintain your code easily.

    * Do you indent at all? If so, how?

    When I use emacs, I follow most of what e-perl wants to do. When I use VIM, I use mostly whatever auto-indent thinks. I used to be more specific about my indenting, but over time, I've found that I can read different styles of indentation without too much trouble.

    * How do you write data structures? How do you access them?

    More broad questions, good :). I'll say "it depends". It depends on how much I plan on using the datastructure, how large the code is, and how complex the interactions will be.

    If its something "simple", I'll just AoAs or HoHs, or a combination of hashes and arrays. As it gets more complex, my datastructures get more complex, storing more and more state.

    * How do you structure your logic?

    I tend more towards a functional style of programming. I like the idea of programming without side-effects and strive to make my code perform that way when its reasonable. When its not, I tend to revert to more OO-style, with objects that store state.

    * How do you call your subroutines?

    usually foo(), at various times with or without (), but I've been trying to reserve ()-less invocation for built-ins only.

    * What kind of naming conventions do you use?

    Whatever seems appropriate. I know that's probably not very clear, but I try to name things tersely, with implied information, as an example, if I have a table named Book, I'll have a column called "name", rather then "book_name", as I feel that the "name" column on the Book table implies that its the name of the Book. In more complex systems, I have been known to be more explicit, as inferring can be more difficult, and its possible that someone will infer differently then you would.

    * What do you consider worth putting into a subroutine? How do you structure them?

    Anything that I expect to use more then once. Anything that I feel the code needs to be able to abstractly "know" about. I've made cube functions that take a len, wid, and height and just return l * w * h, just because I feel that the code needs to "know" how to calculate a cube from 3 dimensions.


    --
    Ben
    "Naked I came from my mother's womb, and naked I will depart."
Re: Commonly accepted style guide?
by radiantmatrix (Parson) on Sep 27, 2005 at 20:36 UTC

    I hate style arguments. Look, we have perltidy. Any 'style' elements you don't like can probably be "corrected" by your .perltidyrc. If they can't, then as long as they don't make the code unintelligable -- and I mean truly unintelligable -- who cares? Adapt, already.

    It's called "style" for a reason. Like styles of dress or decorating, coding style is largely an individual choice. Now, in corporate environments there are style standards, just like there are style standards in the form of dress codes. And, some very basic things can be applied to any public code -- after all, you can't walk around naked most places, there are minimum standards.

    Beyond those "environmental minumums", though, if you're a big burly guy with a perpetual 5-o'clock shadow who prefers to wear a pink tu-tu -- what should I care? One of my cow-orkers insists on Hungarian notation (in Perl). I don't get it, but it helps him and doesn't significantly hurt me: all I ask is that he not get his undies in a bunch if I forget.

    Having arguments about which style is "better" is largely like arguing the finer points of wearing pink tu-tu's. One might make the argument that a pink tu-tu makes just about anyone look silly; but what if someone wants to look silly? What if someone wants to use unless <cond> <action>? What does it really matter?

    To be clear, I'm not talking about mistakes that are sometimes classified as style and have measurable changes. For example, using C-style for loops needlessly (easily causes bugs) or using open FH, "<$var"; (security risk). I'm talking about true "style" arguments.

    Sure, suggest "hey, I see you had this problem -- here's a style tip for you". Hell, I'd suggest to a portly friend that horizontal stripes are probably not the best idea (I know this from experience, btw). But I wouldn't hit him over the head with it if he wanted to wear them anyway.

    <-radiant.matrix->
    Larry Wall is Yoda: there is no try{} (ok, except in Perl6; way to ruin a joke, Larry! ;P)
    The Code that can be seen is not the true Code
    "In any sufficiently large group of people, most are idiots" - Kaa's Law
Re: Commonly accepted style guide?
by ickyb0d (Monk) on Sep 28, 2005 at 17:19 UTC
    not sure but the book "Perl Best Practices" might have some insight onto what you're looking for. We just got one of these in the office and I haven't had to take a look at it yet. But seems like it's at least worth a look.
Re: Commonly accepted style guide?
by bluto (Curate) on Sep 29, 2005 at 15:25 UTC
    Do you feel you can rate the experience level of the author by how the code looks, both in Perl and programming in general?

    For some reason this question comes up from time to time, as if there is some fascination with it, but the answer is still "No". Experience and writing maintainable code don't always overlap.

    I've seen lots of code, some from some very smart people, that looks hideous but runs well. In general it continues to run well as long as they are the ones to maintain it (or they hire someone very smart). Is this good? No, especially not in the long run, but it doesn't say a thing about their experience level. One guy I know does the work of several programmers, with few bugs in his code, but he writes very "old school" C that would make most people cringe.

    In order to determine the experience level, you need to go beyond how it "looks". Just because someone uses...

    for($i = 0; $i < 10; $i++)

    ... in perl doesn't mean they are inexperienced. They may be doing this since they are old C programmers new to perl, or so that other C programmers that work with them could pick up the code easily.

    The real way is to determine experience is to answer the question: How many actual bugs does this code currently (or initially) have? Examining the code sometimes turns these up, but testing and QA bean counting are probably better for this.

      One guy I know does the work of several programmers, with few bugs in his code, but he writes very "old school" C that would make most people cringe.

      So, this guy's code would pass criterion #1, but not criterion #2? To me, well-written code passes both criteria, and (imho) style is an important part of that.


      My criteria for good software:
      1. Does it work?
      2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?
        Can someone else come in, make a change, and be reasonably certain no bugs were introduced?
        Don't you also need to qualify the experience level of "someone else". Some people are baffled by high minded notions like recursion and others can crank out a lisp compiler on a lunch break. Maybe a disclaimer?
        Can a professional of average compentence come in, make a change, and be reasonably certain no bugs were introduced?
        I agree with you. I'm not saying this guy is doing anyone any favors by being extra "productive". I'm just addressing a single point that seems to keep comming up. I'm only saying that you can't determine experience by just taking a quick look at the code.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (8)
As of 2014-12-25 14:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

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





    Results (160 votes), past polls