in reply to Re^3: A quicker way to have protected and private fields?
in thread A quicker way to have protected and private fields?
Something like this I'd guess:
sub new { my $class = shift; my $extends = $class->SUPER::new(@_); $extends->setFlyBehaviour( src::bo::CannotFly->new() ); $extends->setQuackBehaviour( src::bo::CanSqeek->new() ); my $self = { COLOR => undef, }; my @protected = qw/COLOR/; my @private = qw//; my $closure = sub { my $field = shift; if ( exists $self->{$field} ) { grep( /$field$/, @private ) and caller(0) eq __PACKAGE__ || confess "$field is private"; grep( /$field/, @protected ) and caller(0)->isa(__PACKAGE_ +_) || confess "$field is protected"; if (@_) { $self->{$field} = shift; } return $self->{$field}; } else { return $extends->( $field, @_ ); } }; bless( $closure, $class ); return $closure; } sub setColor { my $closure = shift; my $color = shift; &{ $closure }("COLOR", $color); } sub getColor { my $closure = shift; return &{ $closure }("COLOR"); }
Ok, I have to repeat the incantation to mark the private and protected fields as such... for as long as I want to go that far. Here I don't use privates so I could drop the @private and the grep for private fields. In fact I could drop the grep as well and just test on the name before calling confess.
It would be neat to have a cpan class that would do this automagically though...
|
---|