Then earlier today, a very Perlish analogue struck me: on some level, "trait classes" are "method exporters".
For example, here's a hypothetical trivial trait:
package Trait::SelfDumping; require Carp; require Exporter; require Data::Dumper; @EXPORT = qw( dump_self ); sub import { goto &Exporter::import } sub dump_self { my $self = shift; Carp::carp("Self is " . Data::Dumper::Dumper($self) ) } 1;
Now I can add the trait of being self-dumpable to any other class I build:
package My::FooBar; use Trait::SelfDumping ':default'; sub new { ... package main; my $foo = My::FooBar->new(); $foo->dump_self();
A proper traits mechanism should also provide for aliasing method names and for double-checking that other methods that yours depends on have been provided, but those are merely elaborations.
I can imagine an Exporter::Traits module that functioned like Exporter and incorporated the aliasing and missing-methods checks. (Exporter::Renaming already touches on the aliasing aspect. Checking for missing methods is harder, because they may be being provided by another trait, but I presume it can be done.)
Parallel to how Class::Trait works, packages that were going to implement a trait would "use Exporter::Traits" and declare various package variables and subroutines. However, on the caller's side, the interface would follow Exporter, so you could "use" the trait package directly, rather than having to know that it was a trait-driven package.
Have I overlooked something vital in reducing the traits model to a gussied-up Exporter?
And am I right in thinking that viewing this as an Exporter trick makes the concept more accessible to Perl geeks?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Roles as Method Exporters
by chromatic (Archbishop) on Apr 10, 2004 at 17:14 UTC | |
by simonm (Vicar) on Apr 11, 2004 at 05:03 UTC | |
|
Re: Traits as Method Exporters
by stvn (Monsignor) on Apr 11, 2004 at 04:59 UTC |