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

Good Programming is Better

by George_Sherston (Vicar)
on Jan 12, 2002 at 00:49 UTC ( [id://138131]=perlmeditation: print w/replies, xml ) Need Help??

Yes, you may say. But I just realised a couple of reasons why this is more than a platitude. Maybe they're not new realisations to you, but they made me happy, and the background of my realising them (getting slightly better at doing this stuff) also made me happy, so I thought I'd share the moment.

Good Programming is [not just good, it's even] Better [than that]
If I do stuff right, then I find later on to my delight that I can re-use it easily, and it all fits together nicely. The trivial example that gave rise to this realisation was:
(A) I have a function InsertMultipleValues (see below) that I use all the time to insert stuff into db tables. To make it flexible, it accepts arguments in a hashref.
(B) Then just now I was getting some stuff together for insertion into a db, and I thought "what's the best data structure" and I thought "an array of hashes" so that's what I did.
(C) then I came to put it all together and imagine my delight when I found that instead of a half dozen lines I'd expected to have to write at this point, it came down to InsertMultipleValues($dbh,'tbl_name',$_) for @Values;

Good Programming is [readily identifiable, at least in hindsight, as programming that keeps making things] Better
The other thing I realised was - well, it's often a bit contentious what's good programming, but *I* think one way of telling if something is good programming is whether, over time, one finds that it gives rise to happy events like the above. So one can look back and see "huh, that was good programming, as I now know because it did this and that as well as the other". NOW: my challenge is to be able to smell, sense, figure out, whatever, programming choices that will do that, before I write them, rather than noticing them in retrospect. But noticing them in retrospect is a step in the right direction.


sub InsertMultipleValues { #----------------------------------------------------------- # Inserts contents of a hashref into the db table specified # (owes a lot to discussion in SOPW (which I looked for # just now but couldn't find, alas) #----------------------------------------------------------- my $dbh = shift; my $table = shift; my $Inserts = shift; my @cols = keys %$Inserts; my @vals = @$Inserts{@cols}; my $cols = join ',', @cols; my $places = '?,' x @vals; chop $places; my $sth = $dbh->prepare("INSERT INTO $table ($cols) VALUES ($place +s)") or die $dbh->errstr; $sth->execute(@vals) or die $dbh->errstr; }
§ George Sherston

Replies are listed 'Best First'.
Re: Good Programming is Better
by bmcatt (Friar) on Jan 12, 2002 at 01:04 UTC
    As a small addition, I think one of the things that separates the really good developers from the mediocre things is the ability to (consciously or un-) plan for things like this. (IMHO) It's important, when working on the pieces to solve a problem, to think about how they're going to be able to be (mis-)used later.

    If you've got an idea of how something will be used in the future, as well as in the present, you're on your way to thinking about the bigger picture and the evolution of a (module | program | system | whatever). The best programs are those that can change over time without needing substantial rework provided that none of the base assumptions changed. And from there it's a short-ish step to making sure that the assumptions that are made are as few as possible.

    I know that I try my best to make things as flexible / extensible as possible. For me, that means making as few assumptions as possible and figuring out where things are likely to change. Sure, I don't get it right all the time, but being right even 50% of the time can make an enormous amount of difference. That's 50% of the project that doesn't need to be revisited when you're ready for the next release.

      I've had several of these happy events. With my current project, I chose at the beginning to use Object-Oriented Perl, mostly just to learn it, but it also seemed to fit. I've had some training in OO and in Design Patterns, but have never implemented anything with it.

      What a nice surprise when changes that would have taken days now take minutes!

      However, I know that my code could use some improvement. You can always make it more flexible, faster, give it better error handling, etc. I believe that admitting that fact alone makes you a better programmer!

      There is definite satisfaction in finding you've written "good code"...

      On a tangent... The company I work for has a large development project running using Extreme Programming (XP). It stresses good programming, but from a slightly different angle. Here's just a part:

      Break your goal into small piecs

      Work in pairs

      Design your test cases (be thorough) first

      Write your code

      Test your code

      In many cases, later you will find that you could write that method better, faster, etc. With XP, you can now rewrite the method, and you already have the test cases to verify that you didn't break it.

      Moral: You can always write better code. If you know from the beginning your going to rewrite it, then plan for it.

      Also, programming in pairs reduces bugs, and tends to lead to better design because you have more "brain power" (we hope anyway!).

      For an article on XP, and a link to a web site all about it, click here. Brian
      ... and the interesting thing is, that ability to discern ab initio what's going to be broadly flexible and extensible is such a high-level analytical skill that for practical purposes it's something like intuition - like how good chess players work, where you can only go so far with techniques, but at some point you need to have the mysterious "it" that you get by being cool to start with and then working and working and working. If you could bottle it, you could name your price.

      § George Sherston
Re: Good Programming is Better
by FoxtrotUniform (Prior) on Jan 12, 2002 at 01:02 UTC

    Minor nitpick: if you're just preparing a statement, executing it, and throwing the statement handle away, you may be better off just using $dbh->do(...) instead.

    And on the subject of your actual point -- I find this sort of "good programming" arises mostly with orthogonal code: each separate chunk of your code does one thing, does it well, does nothing else, and doesn't depend on anything more than it needs to do its job. Writing orthogonal code (modules, subroutines, etc) gives you a good-sized toolbox of code that you can just plug in and use, and (for me, at least) most of these tools come by decomposing a problem into chunks, then generalizing those chunks just a little.

    --
    :wq
      My rationale for using prepare is so I can use placeholders, so I can have arbitrary numbers of columns, and don't have to think about whether I need quotes. But if one can use placeholders with do, that'd be even sweeter.

      § George Sherston
        You can use placeholders with do. Just make sure you use undef as the first param.
        $dbh->do('insert into blah (?, ?, ?)', undef, $x, $y, $z);
Re: Good Programming is Better
by count0 (Friar) on Jan 12, 2002 at 01:14 UTC
    Warning: Slightly OT rant, branching from this node =)

    The alternative to your InsertMultipleValues() could have been a barebones sub that did only what you needed it to at the time of writing. Worse yet, it could have done so poorly.

    Bad Programming.

    I have the unfortunate task of working on a lot of code that uses Bad Programming, and cuts every corner possible. In the nine months I have spent with my current company, 90% of my time has been spent fixing or extending bad code.

    Enters stage-left: Management
    To make matters worse, when tasked with a new addition to the multitude of systems, I block out code and submit a proposal to my barely-technically-adept PHB.
    "But that's not in the specs for what we need right now! There's no reason to make this a module, just tack it into the end of program XYZ. We do have to pay you for this time you spend, you know!", he'll spout.

    /me sighs.

    I'm left to make my successors' lives equally as miserable as mine has been.
    *Shrug* ... But what do I know, I'm "just a programmer". He (project manager) has more Industry Experience.

    Updates: fixed some minor end-of-the-week-tired-and-i-want-to-go-home, grammar, and tag errors. =)
Re: Good Programming is Better
by runrig (Abbot) on Jan 12, 2002 at 01:39 UTC
    That is very much like the insert_hash example in the DBI docs. FoxTrotUniform is correct in that if you're just going to throw away a statement handle, you may as well use the do() method, but in this case prepare_cached() (as in the insert_hash example) might be better.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (6)
As of 2024-03-19 11:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found