Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

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

by kennethk (Monsignor)
on Nov 14, 2012 at 16:06 UTC ( #1003845=note: print w/ replies, xml ) Need Help??


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

The short answer here is that it's your code and you can make any choice you like, though what you propose is certainly not standard OOP. You could naively add a loop to your new subroutine, like:

sub new { my $proto = shift(@_); my $class = ref($proto) || $proto; my @results; for my $userId (@_) { my $self = { "user_id"=> undef, "user_name" => undef }; bless ($self, $class); my $href = GETSQL("SELECT user_name FROM users WHERE user_ +id = $userId"); @{$self}{keys %{$href}} = values %{$href}; push @results, $self; } return @results; }
Except now you will break the code my $user = User->new($id) because you are returning an array in scalar context, and so your $user variable will contain the length of the array. You could address this with wantarray, but any time you reach for that you need to seriously consider if you are being too clever for your own good.

If I were in your situation, I'd probably leave the constructor alone, and use map if I really felt like I needed to get it done in one line:

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

If you are having noticeable performance problems and have identified your database interaction as the source (see Devel::NYTProf), then you should optimize your database access. Rather than performing each query as a one-off, you can cache the connector and the query itself -- see prepare (or even prepare_cached) in DBI. Or post that bit of code, and we can critique for you.


#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.


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://1003845]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2014-09-24 00:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

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











    Results (243 votes), past polls