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;
In reply to OO - inside-out or by means of a anonymous sub? by gargle
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |