Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: OOP: How to construct multiple instances of a class at once

by tobyink (Abbot)
on Nov 14, 2012 at 16:12 UTC ( #1003847=note: print w/ replies, xml ) Need Help??


in reply to OOP: How to construct multiple instances of a class at once

As per kennethk's suggestion, something like:

my @users = map { User->new($_) } @user_ids;

... is the best way to do this. However, if you find yourself doing that frequently, then you could bundle that functionality up into a class method in the User package.

{ package User; ...; sub multi_new { my $class = shift; return map { $class->new($_) } @_; } } my @users = User->multi_new(@user_ids);

I wouldn't do it directly in new. While new is just a sub and you can technically do whatever you like with it, there is a strong convention that it should return a single instance of the class. Having it potentially return multiple instances will surprise users of your module... and not in a good way.

Bundling it up into a class method gives you the opportunity to take advantage of "encapsulation" at a later date. People using your class will be calling multi_new to construct multiple instances of your class without worrying about what happens inside multi_new. Perhaps in the future you'll discover a new, more efficient implementation for multi_new; you can change the internals and people using your class will get the more efficient behaviour for free.

perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'


Comment on Re: OOP: How to construct multiple instances of a class at once
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2014-09-20 04:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (153 votes), past polls