First of all, is there a preferred style for "new" constructors? Specifically one which will be taking hash value/key pairs as attributes?
A summary of Perl Best Practices (TM) can be found on the Best Practices(TM) reference card. It does not make any pronouncements on the argument list for a constructor. The key-value syntax is a good choice, but you probably want to include a mod 2 test (die "Uneven list" if @_ % 2) to make sure the list is actually balanced. A single hash-ref is also a popular choice. See Moose::Manual for how the most standard issue object object system does it.
Secondly, is there a way to tell how many objects have been created/exist in a particular class?You could add a counter to your constructor, and then provide an accessor to the counter, e.g.
with the possibility of also adding a decrement to the destructor.my $obj_count = 0; sub new { my $class=shift; my %params=@_; my $self={}; $self->{$_}=$params{$_} foreach keys(%params); bless($self, $class); $obj_count++; return $self; } sub get_count { return $obj_count; }
And lastly, what is the best way to access individual object attributes? Always through a method or can you access them directly?This one, best practices does weigh in on. Always through a accessor. That allows for a layer of abstraction between the object itself, makes you insensitive to implementation changes, and allows for side-effects and internal mutations of the class if the designer needs them.
Side note: if this is not just a learning exercise, consider using a declarative object system, like Moose or one of its lighter-weight derivatives.
#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.
In reply to Re: OO best practice basic questions
by kennethk
in thread OO best practice basic questions
by Amblikai
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |