However, I prefer using closures because I can define private and protected fields with ease.
I appreciate that you put some effort into drafting a tutorial-style meditation. However, in both this post and A quicker way to have protected and private fields?, you show a clear bias for closure-based objects over any other type. (You do realize that Objects with Private Variables was written in 2000, right?)
At the very least, for clarity, I think that you should retitle your post to something like "Closure objects with public, private, and protected fields".
Morever, I think that your piece would be much stronger if you explored several ways to do public, private and protected fields and articulated the pros and cons of each. Some people might reach different conclusions on whether the pros and cons lead to the same place.
For example, with a closure based object of the type you articulate, every private field access (from within __PACKAGE__) requires:
Contrast that with an inside-out object:
package Duck::Secret; use Class::InsideOut qw( private id register ); private secret => my %SECRET; sub new { my $self = register( bless \(my $s), shift ); $SECRET{ id $self } = int( rand(100) ); return $self; } sub guess_secret { my ($self, $guess) = @_; return $guess == $SECRET{ id $self }; }
Accessing that inside-out private field requires:
So, in this example, if someone has lots of private fields and few (or no) protected fields, inside-out objects seem likely to have much better efficiency.
Adding protected accessors for inside-out objects is also easy:
# continuing previous code example sub secret { my $self = shift; die "Secret is a protected field" if ! caller(0)->isa( __PACKAGE__ ) +; $SECRET{ id $self } = shift if @_; return $SECRET{ id $self }; }
That still has less overhead than a closure-based object.
So, maybe you'd like to consider a fuller treatement of the subject before declaring closure-based objects are the way to go.
-xdg
Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.
In reply to Re: Working with public, private, and protected fields
by xdg
in thread Closure objects with public, private, and protected fields
by gargle
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |