On Sun, 17 Aug 2003, Nigel Rantor wrote:
> So, I want to extend an OO package.
Just so we get our terminology in a row, the name for a collection of code
that you load via 'use' into a package is 'module' in Perl. A module may
have a package, but the package is just a namespace - so you don't
normally extend a package, but extend a module. Does that make sense?
> The methods I want to add don't require access to any of the object's
> data and are just built upon the methods that the object already provides.
>
> What would be the best way to hoist these methods into the original
> package's name space?
You shouldn't. Really. You should subclass the other method.
package Foo;
use base qw(Bar);
sub fred
{
my $self = shift;
$self->wibble;
$self->wobble;
}
Then:
use Foo;
my $foo = Foo->new(); # the new method is called automatically in Bar.
> Alternatively would you simply not pollute someone elses namespace?
Yes. Though if you really really really need to you could do this in
whatever module you wanted
Foo.pm
=======
package Foo;
sub Bar::fred
{
...
}
1;
Meanwhile in your code
use Bar; # load Bar
use Foo; # load Foo, which will load extensions into Bar (the fred method
# in the above explanation
But don't do that. Really. No, really, really, really. No REALLY REALLY
REALLY.
Years of OO design have shown us that this is a bad idea.
> If you don't pollute their name space then do you have to release a
> class that has the extensions in it and make people instantiate that
> class?
Yes, this is the normal thing to do.
> How do you deal with other people who want to extend the same
> base?
The simple answer is "you don't". The complicated example is that you
first write the first extension module which uses the first class as it's
base class (so Foo extends Bar,) and then you write a second class that
extends that class (so Zeb extends Foo), meaning that class indirectly
extends the first class (so Zeb extends Bar.) The really really
complicated solution is to use multiple inheritance, but I'm not going to
explain that unless I'm forced to.
> If you wanted to make a package called Base::Spline, how would you do it?
package Base::Spline;
use base qw(Base);
...
> Cheers,
>
> Nige
No problem mate. I highly suggest getting a copy of Damian Conway's book
"Object Orientated Perl" (Manning Press) that explains Perl's OO system
better than any other book on the market.
Mark.
--
#!/usr/bin/perl -T
use strict;
use warnings;
print q{Mark Fowler, [EMAIL PROTECTED], http://twoshortplanks.com/};