[Israel.pm] OO Perl and Exporter
gaal at forum2.org
Tue Dec 28 06:26:13 PST 2004
Offer Kaye wrote:
> Question for the OO gurus - assuming I supply all the required
> methods, setters and getters, etc., would I ever want to use @EXPORT,
> or even @EXPORT_OK? Doesn't that defeat the idea of encapsulation?
Answering out of place since I'm no OO guru--
Export doesn't scale in the general case. It has similar problems to
multiple inheritance. Undiscriminating @EXPORT is almost always a bad
Exporing (or, from the user code, a better name would actually be
*importing*) is mostly a convenience: after all, you can always use
If the length bothers you, you have several possibilities. First, if
this is your code, you can write class methods that work on instances,
as others have pointed out. I'm not sure I like this, though, if it's
only to save keystrokes. Not that saving keystrokes is bad, of course,
but for larger projects it's handy to know what operates on a class an
what on an instance.
FWIW, this works:
my $class = "Very::Long::Class::Name" .
my $count = $class->instance_count(); # class method
So you don't have to call $obj->instance_count(). You can do the same
thing with $class->new, so you really only have to type the long class
name once. The only hit you take is keeping the scalar "$class" around,
and probably a runtime performance degregation you would be good not to
care about. :-)
Yet another option is to alias either the namespace or particlar methods.
I can't say I go for these, though. *I didn't check*, but I have a hunch
they break with some methods that check the value of $class. Speaking of
which, using the "$class = ...; $class->class_method()" approach lets
you upgrade your code to a subclass relatively easy, since you only need
to change one place. (Designing with factories can achieve the same
Careful use of deliberate namespace, er, conflation can give you
something that actually affects design: now we are talking of mixins.
Two Perl implementations:
Now, if you want to do this boldly, you should also look into traits,
and roles, which aren't easy to grok but which are planned for perl6.
(The last link is me starting out trying to explain interfaces, and
getting traits explained to me.)
Hope this wasn't too long or rambling,
Gaal Yahas <gaal at forum2.org>
More information about the Perl