Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

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

by kennethk (Abbot)
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.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2017-07-24 01:40 GMT
Find Nodes?
    Voting Booth?
    I came, I saw, I ...

    Results (347 votes). Check out past polls.