Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Object insanity and data hiding

by blakem (Monsignor)
on Sep 09, 2001 at 09:49 UTC ( [id://111250]=note: print w/replies, xml ) Need Help??


in reply to Object insanity and data hiding

I would highly recommend reading Damian Conway's Book Object-Oriented Perl for a project like this. Just flipping through my copy, I came accross this example on page 92, where he address the issue of data hiding by using the AUTOLOAD function.
package CD::Music; use strict; use vars '$AUTOLOAD'; # Keep 'use strict' happy { my %_attrs = ( _name => undef, _artist => undef, _publisher => undef, _ISBN => undef, _tracks => undef, _rating => undef, _room => undef, _shelf => undef, ); sub _accessible { exists $_attrs{$_[1]} } } sub AUTOLOAD { my ($self) = @_; $AUTOLOAD =~ /.*::get(_\w+)/ or croak "No such method: $AUTOLOAD"; $self->_accessible($1) or croak "No such attribute: $1"; $self->{_read_count}++; return $self->($1); }
This will dynamically create methods such as getname to access the underlying data, rather than letting someone poke at it willy-nilly. This keeps your access methods and your data in sync. It also allows for easier error checking, since all your methods are being dynamically defined in one place.

-Blake

Replies are listed 'Best First'.
Re: Re: Object insanity and data hiding
by thpfft (Chaplain) on Sep 09, 2001 at 14:36 UTC

    I don't think this will help: synapse0 is using a generic get() because s/he doesn't know what the keys of the config hash are going to be. explicit methods - or autoload fields - won't fit.

    As for the question of how to make sure the contents of the config hash are only visible to the prescribed methods, I think the answer is probably a closure object, though i've never had occasion to use one this way. 'Closures as Objects' in perltoot should provide all that's needed.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://111250]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (5)
As of 2024-04-25 10:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found