Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Poor Man's Prototyping?

by jarich (Curate)
on Nov 25, 2001 at 07:20 UTC ( [id://127348]=note: print w/replies, xml ) Need Help??


in reply to Poor Man's Prototyping?

This is a really common way to do things in Perl OO, but need not be limited to that. It gives you the opportunity to allow defaults etc.

Something I do a lot (in OO) is this:

my %defaults = ( cat => 1, dog => 2 ); my @allowed = keys(%defaults); # you might allow others in here too. sub new { my $class = shift; my %args = (%defaults, @_); my @hash{@allowed} = @args{@allowed}; # ignore arguments # that we're not expecting. # do any specific checking here. my $self = \%hash; return bless ($self, $class); }
The key point here is that this makes it easy for the user to pass the same set of arguments to a subroutine/constructor and for the class to only use the ones it wants. What is more, this method of passing arguments means that the user doesn't have to remember what order things go in.

That's probably the biggest advantage of this method passing, not for prototyping purposes but that it saves the user having to remember argument order, especially if you have "optional" arguments.

Defaults can be done when you use shift too.

sub mysub { my $cat = shift || 1; # etc }

By the way, putting the defaults hash outside of your subroutine means that you need build it only once (and you can modify it during the program if needed, but this can be a bad thing too).

Replies are listed 'Best First'.
Re: Re: Poor Man's Prototyping?
by dragonchild (Archbishop) on Nov 26, 2001 at 21:14 UTC
    While this is a very good thing to do, as it protects you quite well, it can cause further problems when it comes to user expectations. You have to make sure that the contract between this object and the rest of the world is well-documented. Otherwise, a user will pass in 'bird' and not know why 'bird' isn't there.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

      I agree. Documentation is essential. But so it is for all interfaces. If I'm calling by position, the user still has to understand what order the items are required in. At least with named parameter passing the user can afford to forget the exact ordering sometimes. :)

      (Good point though. ++)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2024-05-28 08:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found