package Obj; my %bar_cache; sub new { my ($class, %args) = @_; my $dbh = $args{dbh} my $cfg = $args{cfg}; my $obj_id = $args{obj_id}; my $in = { dbh => $dbh, cfg => $cfg, foo => {}, bar => {}, }; my $self = bless $in, $class; # foo is a result of a different query for every obj_id $in->{foo} = $self->foo($obj_id); # The following part is the only part I am still confused about. # Should I use something like Memoize here? # # bar changes only once per, say, every 5000 objects, # and the resulting query from $self->bar is a very # large set (thousands of rows), so it makes sense to # query the db only when bar changes. So, for obj_id # 0 through 4999, bar remains the same, then for obj_id # 5000 through 9999 a new bar is returned, and so on $in->{bar} = $self->bar($obj_id); return $self; } sub bar { my ($class, $obj_id) = shift; if ($self->{bar}) { return $self->{bar}; } else { if (exists $bar_cache{$obj_id}) { $self->{bar} = $bar_cache{$obj_id}; } else { my $dbh = $self->dbh; my $bar = query_dbh_for_bar_execute($obj_id); # Empty bar_cache of old values %bar_cache = (); $bar_cache{$obj_id} = $bar; $self->{bar} = $bar_cache{$obj_id}; } return $bar; } }