[Israel.pm] OO Perl and Exporter

Gaal Yahas 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
idea.

Exporing (or, from the user code, a better name would actually be
*importing*) is mostly a convenience: after all, you can always use
Fully::Qualified::function().

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" .
          "::I::Mean::Really::What::Where::They::Thinking";

      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.

      http://search.cpan.org/dist/Method-Alias/
      http://search.cpan.org/dist/Package-Alias/

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
effect.)


Careful use of deliberate namespace, er, conflation can give you
something that actually affects design: now we are talking of mixins.
Two Perl implementations:

      http://search.cpan.org/dist/mixin/
      http://search.cpan.org/dist/Class-Mixin/

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.

      http://www.cse.ogi.edu/~black/publications/TR_CSE_02-012.pdf
      http://search.cpan.org/dist/Class-Role/
      http://search.cpan.org/dist/Class-Roles/
      http://search.cpan.org/dist/Class-Trait/
      http://perlmonks.org/?node_id=379101

(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

-- 
Gaal Yahas <gaal at forum2.org>
http://gaal.livejournal.com/



More information about the Perl mailing list