http://www.perlmonks.org?node_id=412680


in reply to Re: Use method/function signatures with Perl
in thread Use method/function signatures with Perl

Juerd wrote: There is a lot of readability to be gained by just writing it differently:

sub name { my $self = shift; $self->{name} = shift, return $self if @_ == 1 croak "Unknown arguments to name" if @_; return $self->{name}; }

Minor point: readability is often subjective. I'm not sure if your code is easier to read, but it is more concise. However, it's still not as easy to read (IMHO) is MMD:

Major point: Perl has an entire class of bugs not found in other languages and in our debating the merits of how to deal with it, both of us have fallen victim to this bug.

Your code has a bug. Specifically, mine does not allow a reference to be assigned to name. Your code does. This seems like a minor nit but this goes to the code of the problem I am trying to solve. Consider the following snippet from the POD of my module:

sub name { my $self = shift; $self->set_name(@_) if @_; # I forgot the return! return $self->{name}; } sub set_name { my $self = shift; $self->{name} = shift; return $self; }

I didn't intend to put a buggy example in my POD, but my bug and your bug are in the same class of bug. Specifically, forcing programmers to check the number and type of arguments is to shift programming burden to the programmer when it can easily be handled by the computer. I gave a live testing demo at Portland Perl Mongers and many who actually did testing admitted they skip this validation in their actual code unless the code is a critical part of the system. Why should this be done? Most languages provide this validation with signatures (though this still only validates type and not domain.)

Cheers,
Ovid

New address of my CGI Course.

Replies are listed 'Best First'.
Re^3: Use method/function signatures with Perl
by Juerd (Abbot) on Dec 07, 2004 at 19:02 UTC

    Your code has a bug. Specifically, mine does not allow a reference to be assigned to name. Your code does.

    A major point indeed. I'll abuse it for my own purpose, though: it's the unreadability that made me overlook it! :)

    But the fix is simple and doesn't hurt readability much. You are right that accessor methods are error prone in multiple ways. Fortunately, simple lvalue accessor methods don't have this problem.

    Juerd # { site => 'juerd.nl', plp_site => 'plp.juerd.nl', do_not_use => 'spamtrap' }