in reply to My first stab at OO perl...
sub add_expense { # takes Expense object as argument and adds it to _E +XPENSES array my $self = shift; my $newexp = shift; my @expenses = @{$self->{_EXPENSES}}; $newexp->{_ID} = $#expenses + 1; push(@expenses,$newexp); $self->{_EXPENSES} = \@expenses; }
Where are the problems with this code?
We have a couple. The first is simply syntax:
my $self = shift; my $newexp = shift;
Simple, clean, one look gives you all the incoming sub arguments, expands easily:
my ($self, $newexp) = @_;
my @expenses = @{$self->{_EXPENSES}};
Why would you do this? with this one operation, you have just duplicated the entire array for no real gain. Certainly if you were going to reference the array many times it *might* be worth it, or if you were likely to bail part-way through your modifications and want the array to remain as it was until you make your final change, but in this instance its pure inefficiency to no value. If you don't feel comfortable referencing @{$self->{_EXPENSES}} twice, then do my $expenses = $self->{_EXPENSES} instead and use the reference.
The entire ID concept gives me shivers. This is the kind of code people wrote when they didn't have associative arrays, with "rehash" methods to compact down a data structure that had elements tagged for deletion (undef) etc. Its simply not healthy, your interface as it stands allows you to add a single expense twice (BAD, _ID would be reset and the Expense object would be confused), requires compacting, does not guarrantee unique ids (create Expense, keep reference, add, delete, rehash, add new Expense, doh, has same ID as old reference), and is basically hard work.
Instead, use an associative array keyed by the reference. If you need to maintain order you can use one of the more advanced structs on CPAN to do that at the same time, but the advantages of an associative keyed by reference are that you never have duplicate IDs, IDs don't need to be explicitly tracked, adding a single expense multiple times is fine and you never need to rehash.
My final code?
sub add_expense { # takes Expense object as argument and adds it to _E +XPENSES array my ($self, $newexp) = shift; $self->{_EXPENSES}{$newexp} = $newexp; }
:)
|
---|
Replies are listed 'Best First'. | |
---|---|
Re2: My first stab at OO perl...
by dragonchild (Archbishop) on Jul 17, 2002 at 16:46 UTC | |
by PhiRatE (Monk) on Jul 17, 2002 at 22:48 UTC |