in reply to What habits do you have to avoid introducing bugs?

I have a number of habits that I use regularly to prevent syntax and certain simple semantic errors.

Firstly, I always type the parens first, then go back an fill in the contents:

if () if () { } if () { } else { } if ($foo) { } else { }

Similarly, I write file-reading loops outside-in:

open my $file, ... open my $file, ... close $file; open my $file, ... while () { } close $file; open my $file, ... while (<$file>) { chomp; } close $file;

Or fire-and-forget database connections:

my $db = DBI->connect(...); END {$db and $db->rollback and $db->disconnect}

This way I can do race ahead doing what needs to be done, and I know that no matter how my programs ends, everything will be undone. It's only after I've tested that the desired results are achieved do I go back afterwards and change the END to commit the db changes.

I know there are auto-completion editors that generate this boilerplate for you, but I've never come across one I could really come to terms with. The main point is that your code should always be runnable (assuming you finish the statement you're writing).

I find this cuts out a lot of edit-compile-kaboom cycles. Once you are confident that the program will run each time without syntax errors, I find you can concentrate a lot more on the problem itself, and this accrued concentration naturally helps you pay more attention to the the larger issues. I hate wasting five minutes trying to track down a poorly-closed heredoc. The time wasted on this issue is an interruption in concentration about the problem you're really trying to solve. Get that sorted out, and you reduce the chance of creating subtle errors in the larger picture.

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

Replies are listed 'Best First'.
Re^2: What habits do you have to avoid introducing bugs?
by toolic (Bishop) on Feb 06, 2008 at 14:39 UTC
    ++

    The editor I use (NEdit), as I'm sure every editor with a modicum of intelligence, allows me to create macros which automatically create common empty structures as you have mentioned (if-elsif-else, etc.). The small investment in time it takes to set these up pays off big in the long run.