PBP: 063 If Blocks

The first entry in the “Control Structures” group regards the humble if statement.  Perl being perl, the if statement is more complex than it looks, and the Best Practices casually state, “… always use the block form of if.”

Of course, the next practice gives you an exception, and one that I take further than this, but I’ll discuss it more there.

In general, I feel this is the right idea, but that there are more exceptions than the book allows.  Many people will disagree with me on this, and some of them have really good reasons.  They’re just ones I don’t agree with.

My biggest disagreement with “only use the block if” is when doing parameter validation at the start of a function.  I find it useful to be able to say:


sub stupid {

my $color = shift;

my $flavor = shift;

my $size = shift;

 

die "Need to set a flavor" unless defined $flavor;

die "Need to set a color" unless defined $color;

$size = 'small' || $size;

die "Blue is only available in size huge" if ($color eq 'blue' and $size ne 'huge');

# Do other stuff

}

Terrible, contrived example, but it shows the kind of validation I’m discussing.  The chunk of tests right at the start of a function that validate that yes, indeed, it has been called with sensible values and isn’t going to scribble everywhere or order -1 pizzas to the White House.

I find this kind of construct useful, and I prefer to see the postfix if used there because I can read the messages easily.  The cases aren’t as important; they just implement the check for the message.  I’ve heard it argued that this is backwards, but I hate the extra verbiage it adds to the start of the function to use the block if, and I like it even less when you try and smash the block if on to one line.

If the conditions are complex, they should be a block if, no matter what, though.

And, very often, more useful tools such as Params::Validate or the Moose/Moo equivalent can make that simpler yet.

 

2 Responses to “PBP: 063 If Blocks”

  1. I think the “extra verbiage” is what steers people to (over) use trailing conditionals: one less set of parens and braces. The question is, does that just save a bit of typing, or does it make it easier to read later? And (the kind of point Conway tends to raise) does it stay readable during maintenance after it’s edited 6 times and different features are added?

    And there’s still another way, by the way… An alternate idiom I often use:
    ($DEBUG) && print STDERR “Debugging again”;

    In that case, the $DEBUG up front acts something like a comment character, it tells you immediately you’re not looking at one of the lines of real code.

  2. Aaron Priven says:

    I always have to work out the truth tables in my head whenever somebody uses && or || as control statements. I find “x if y” much, much clearer than “y && x”.

Leave a Reply