in reply to Re: How to write better code?
in thread How to write better code?

I agree with other comments regarding the advisability of use CGI; if parsing CGI. I also agree with your advice to the OP about meaningful variable names. However, while the code does what it is meant to do, I think it might be more readable if the foreach loop and the intermediate variables are dispensed with

my $cgi_query_string = "name=alex&sex=m"; my %query = map {split m{=}} split m{&}, $cgi_query_string;

I realise this might be a step too far for some but I find it easier to see the wood for fewer trees. Others may (and probably will) disagree.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^3: How to write better code?
by jbert (Priest) on Dec 04, 2006 at 17:18 UTC
    It's an interesting point. I almost put in a paragraph on this (saying that some people would suggest dropping the naming variables).

    I tend to view naming vars almost a substitute for comments. They can be a way of better documenting your intent. I mused about that a bit here.

    That said, there's also a lot to be said for brevity, and I like your code too :-).

    If I'm honest, I suspect I'd have dispensed with the @components intermediate array, but written out the foreach. I think this is because I rarely think of assigning arrays to lists (and avoiding using a side-effect like $query{$x} = $y in a map clause is one of my reasons for using an explicit foreach). Maybe I should do that more often.

    One hint is that I had a little trouble coming up with a good name for the intermediate array - always a good sign that it probably isn't necesary/desirable.

Re^3: How to write better code?
by imp (Priest) on Dec 04, 2006 at 17:20 UTC
    Your implementation using map instead of foreach is slightly more readable, but will be more cumbersome to maintain and debug if additional parsing is required. It is likely a short-term win that will result in a comment block that is larger than the code after a few upgrades are made.

    Another weakness of using map for this is that CGI allows a parameter to have multiple values, but the code you provided will only use the last value.

      If the task becomes more complex then I would almost certainly rewrite the code with more explicit control structures and descriptive variable names rather than jump through hoops making the map fit. I am only throwing away one line, when all's said and done.

      I agree with your comment about CGI and said as much at the top of my post, which was more a comment on the code snippet itself and it's legibility rather than it's suitability for parsing CGI.

      Cheers,

      JohnGG