gargle has asked for the wisdom of the Perl Monks concerning the following question:
Dear Monks,
I'm a bit puzzled... :( I have implemented a composite pattern and wanted to reuse a sub called getCreditAccounts() I have already written down.
getBalansCreditAmount() calls all accounts in the CREDITACCOUNTS array and reapplies itself to get the credit amounts stored there. getCreditAccounts(), used by getBalansCreditAmount() returns an array with accounts. (the sub is listed below)
I also have a addCreditAcount() to add accounts to the CREDITACCOUNTS array. In this sub I first fetch the parameter, a new account. Then I want to get the contents of CREDITACCOUNTS and push the new account in it. I do this byy taking the reference from &{ $closure }("CREDITACCOUNTS") in an $accountref and pushing the new account in the de-reference.(the sub is listed below)
However, I feel like I didn't reuse getCreditAccounts() because of the funny looking my $accountsref = &{ $closure }("CREDITACCOUNTS")
sub new { my $class = shift; my $name = shift; my $self = { NAME => $name, CREDITAMOUNT => Math::BigInt->new(0), DEBETAMOUNT => Math::BigInt->new(0), CREDITACCOUNTS => [], DEBETACCOUNTS => [], }; my $closure = sub { my $field = shift; if (@_) { $self->{$field} = shift; } return $self->{$field}; }; bless( $closure, $class ); return $closure; }
# public to add accounts to the creditaccounts sub addCreditAccount { my $closure = shift; my $account = shift; my $accountsref = &{$closure}( "CREDITACCOUNTS" ); push @{ $accountsref }, $account; }
# public getBalansCreditAmount to get the amount of all accounts sub getBalansCreditAmount { my $closure = shift; my $totalCreditAmount = $closure->getCreditAmount(); for my $balans ( $closure->getCreditAccounts() ) { $totalCreditAmount += $balans->getBalansCreditAmount(); } return $totalCreditAmount; }
# private getCreditAccounts sub getCreditAccounts { caller(0) eq __PACKAGE__ || confess "getCreditAccounts is private" +; my $closure = shift; my @accounts = @{ &{$closure}( "CREDITACCOUNTS" ) }; return @accounts; }
A a lot of retyping seems to just have happened. Is there a way to reuse getCreditAccounts() in the addCreditAccount sub to make the code a bit clearer to understand?
ps: I need to check for circular references in this code. This I'll implement this later!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: composite pattern, best practice, pushing into an array in a hash, reusing the get array method
by vladb (Vicar) on Feb 13, 2006 at 21:23 UTC |