Hello HipDeep, and welcome to the Monastery!
I've also seen quite a few references to the concept that you should never access data structures directly, that you should always use a method. But I'm not sure that would apply directly in this case.
That is quite correct, and I don’t see why it wouldn’t apply in this case. Here is how I would refactor the modules:
package Monks::Data; use strict; use warnings; use parent 'Monks'; BEGIN { use Exporter(); our $VERSION = 20160808.00; our @ISA = qw(Exporter); } sub version { $Monks::Data::VERSION; } { my @fluffy; BEGIN { @fluffy = qw( Rabbits Minks Cats ); } sub is_fluffy { my $animal = shift; for (@fluffy) { return 'Yes' if $animal eq $_; } return 'No'; } } { my %textures; BEGIN { %textures = ( Rabbits => 'soft', Minks => 'supersoft', Cats => 'coarse', ); } sub get_texture { my $animal = shift; my $texture = 'unknown'; $texture = $textures{$animal} if exists $textures{$animal}; return $texture; } } 1;
package Monks; use strict; use warnings; use Monks::Data; BEGIN { use Exporter; our $VERSION = 0.01; our @ISA = qw(Exporter); } sub version { $Monks::VERSION } sub new { my $class = shift; my $self = { @_ }; bless $self, $class; return $self; }; sub check_fluffy { return Monks::Data::is_fluffy($_[1]); } sub find_fur_texture { return Monks::Data::get_texture($_[1]); } 1;
The value of this indirection is that it allows the implementation of package Monk::Data to be changed at a later date without impacting the code of its client(s). This is a general OO rule: keep the implementation separate from the public interface, and keep it private.
There are also some situations where I need to access the same type of data that is hard-coded into the main module. The common answer for that seems to be to copy that data into the object when it's created, but that seems inefficient in my case because I have some pretty large structures defined to handle a variety of cases where any individual object is only going to need a sliver of that data.
I don’t understand this. Can you elaborate? — preferably with example code.
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
In reply to Re: OO manner of accessing static variables in a subclass?
by Athanasius
in thread OO manner of accessing static variables in a subclass?
by HipDeep
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |