On 2002.05.19, Tim Hammerquist <tim / vegeta.ath.cx> wrote:
> > Is it typical to test values as they're set (when you execute the
> > regex) or right before you use them?  What's the more defensive way of
> > coding?
> 
> Well, depending on how many capturing groups you set up in the regex,
> you can save yourself a lot of checking. eg, if you don't check the
> success of the match, you end up having to check any number of $[1-9]
> vars... or you could just check the regex success once and save the
> trouble.
> 
> Basically, if the match fails, you don't have to check any values.

Yikes.

  def foo(something)
    something =~ /.../
    or_other = $1
    bar(or_other)
  end

  def bar(or_other)
    ...
  end

Are you saying that if you test the success or failure of the
match in foo(), that bar() doesn't need to test its inputs?

> Most Perl code from gurus checks the match success immediately.
> 
> Most Ruby idioms do the same.

Really?

-r--r--r--    1 root     root       217854 Oct  5  2001 /usr/lib/perl5/5.6.1/CPAN.pm

   3086     # read header
   3087     my($line_count,$last_updated);
   3088     while (@lines) {
   3089         my $shift = shift(@lines);
   3090         last if $shift =~ /^\s*$/;
   3091         $shift =~ /^Line-Count:\s+(\d+)/ and $line_count = $1;
   3092         $shift =~ /^Last-Updated:\s+(.+)/ and $last_updated = $1;
   3093     }
   3094     if (not defined $line_count) {
   3095
   3096         warn qq{Warning: Your $index_target does not contain a Line-Count header.
   3097 Please check the validity of the index file by comparing it to more
   3098 than one CPAN mirror. I'll continue but problems seem likely to
   3099 happen.\a
   3100 };
   3101
   3102         sleep 5;
   3103     } elsif ($line_count != scalar @lines) {

Maybe this portion of CPAN.pm wasn't written by a Perl guru.
You are right though, that it is more common to find regex
success immediately with the regex evaluation.  Perhaps
it's because with Perl, you can't know if $1 is valid (applies
to the regex you just evaluated) _unless_ you test if the
regex succeeded, which _forces_ you to test for the regex
success.  Ruby doesn't force you to do this, so the only
reason for it to be a Ruby idiom is because it's a carry-over
from Perl.

In Ruby, which is more OO than Perl, I'd imagine that the
idiom would involve more decoupling between objects.  The
object receiving the message should be responsible for
determing the validity of its inputs, not necessarily
the sender.

-- Dossy

-- 
Dossy Shiobara                       mail: dossy / panoptic.com 
Panoptic Computer Network             web: http://www.panoptic.com/ 
  "He realized the fastest way to change is to laugh at your own
    folly -- then you can let go and quickly move on." (p. 70)