gargle has asked for the wisdom of the Perl Monks concerning the following question:
I just bought Damian's Perl Best Practices and after reading I was left wondering about the 'best' way to do OO. I understand his reasoning about inside-out objects and the big "why it's better".
However, I always thought anonymous subs would also provide the same 'services' as inside-out objects...
Or am I really missing something? (this poor soul has to work with java code - it may have poisoned my mind :(
It seems to me the following is thread-save and encapsulates all the data...
package Rekening; # class for storing information about an account and doing a little qu +ick credit transaction use warnings; use strict; use Carp; sub new { my $class = shift; my $self = { ACCOUNT => undef, NAME => undef, BALANCE => 0, }; my $closure = sub { my $field = shift; if (@_) { $self->{$field} = shift; } return $self->{$field}; }; bless ($closure,$class); return $closure; } # public accessors sub account { &{ $_[0] }("ACCOUNT", @_[1 .. $#_]) } sub name { &{ $_[0] }("NAME", @_[1 .. $#_]) } sub balance { &{ $_[0] }("BALANCE", @_[1 .. $#_]) } # protected method printMe sub printMe { caller(0)->isa(__PACKAGE__) || confess "cannot call protected meth +od\n"; my $self = shift; print $self->account . " " . $self->name . " " . $self->balance . "\n"; } # private method add my $add = sub { my $self = shift; my $amount = shift; $self->balance($self->balance+$amount); }; # private method padd sub padd { my $self = shift; my $amount = shift; caller(0) eq __PACKAGE__ || confess "cannot call private method"; $self->balance($self->balance+$amount); } # public method credit sub credit { my $self = shift; my $amount = shift; $self->padd($amount); } 1;
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: OO - inside-out or by means of a anonymous sub?
by ikegami (Patriarch) on Jan 12, 2006 at 16:08 UTC | |
by xdg (Monsignor) on Jan 12, 2006 at 21:40 UTC | |
by Roy Johnson (Monsignor) on Jan 12, 2006 at 16:26 UTC | |
by ikegami (Patriarch) on Jan 12, 2006 at 16:30 UTC | |
Re: OO - inside-out or by means of a anonymous sub?
by revdiablo (Prior) on Jan 12, 2006 at 17:09 UTC | |
Re: OO - inside-out or by means of a anonymous sub?
by diotalevi (Canon) on Jan 12, 2006 at 19:01 UTC | |
Re: OO - inside-out or by means of a anonymous sub?
by Perl Mouse (Chaplain) on Jan 12, 2006 at 17:03 UTC |