in reply to OO manner of accessing static variables in a subclass?
A second general guideline is that if you want to make the data interchangeable, don't use direct access to fields, encapsulate the data in method calls. To that end, either move the methods sub check_fluffy and sub find_fur_texture into package Monks::Data;, or wrap the fields into accessor methods like sub get_fluffy and sub get_textures, then the methods Monks::check_fluffy and Monks::find_fur_texture can call those methods to get the data.
Next, two suggestions for loosening the coupling between package Monks; and package Monks::Data;. Option A, don't use subclassing, instead make the data object Monks::Data a field on the class Monks - again encapsulated in a getter/setter method. Then that object could be passed to the constructor: my $object = Monks->new( data => Monks::Data->new );. That way, Monks doesn't need to care about the details of the data class, it simply needs to know that the data class has two methods e.g. get_fluffy and get_textures.
Option B, if you really want to use super/subclasses (whether that's the best design choice in this case is debatable, depending on what the rest of your class structure looks like), have package Monks; define abstract methods within itself that must be overridden in the subclasses. So for example, in your package Monks; add sub is_fluffy { croak "abstract method must be overridden" }, and in package Monks::Data; add sub is_fluffy { my $self = shift; my $who = shift; return 1 if grep { /\Q$who/ } qw/Rabbits Minks Cats/; return; }. Then, the calling script needs to do my $object = Monks::Data->new; instead of Monks->new. Now, the interesting thing about this approach is that other methods in Monks can still call the abstract methods in Monks - for example, in Monks, you can do sub check_fluffy { my $self = shift; return $self->is_fluffy(shift) ? "Yes" : "No"; }.
The above concepts apply to any OO design, so if that's what you're practicing, then using Moose or Moo just saves you some typing. Also, BTW, objects don't usually use Exporter.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: OO manner of accessing static variables in a subclass?
by HipDeep (Acolyte) on Aug 10, 2016 at 05:46 UTC |