Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

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'

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1003847]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2018-05-22 20:15 GMT
Find Nodes?
    Voting Booth?