[Pdx-pm] Poll: traits
chromatic
chromatic at wgz.org
Sat Nov 19 11:22:41 PST 2005
On Sat, 2005-11-19 at 10:54 -0800, Eric Wilhelm wrote:
> "A trait is essentially a group of pure methods that serves as a
> building block for classes and is a primitive unit of code reuse."
>
> So, can you spell that in Perl? It sounds suspiciously like it's
> nothing more than a module that allows you to import some methods into
> your namespace. Or is that a mixin?
It's a lot more than a mixin. It's an abstraction that gives a
semantically useful name to a group of methods.
Occasionally people show up in Perl QA to ask "I have these functions
that print their output and I want to collect that output instead!" The
answer is somewhere between select(), tie(), and IO::Handle or another
module. You really have to know what you're doing to make it work.
You also could define a trait for an appendable collection of lines.
That might represent a file (you can print to it) or an array (same) or
a log (if it expires the oldest content) or a cache (the same).
If every place you want to append a line to something you check that
what you're going to use does that trait -- instead of being a
filehandle or an array or however it implements that trait -- you get a
lot more flexibility. In particular, you're checking for the
appropriate *intended behavior* of an object, not its implementation.
Likewise you could have a KeyedLookup trait for a hash or a cache or a
remote object storage system or whatever.
The important thing is the name of the collection of methods. You can't
just check that the object you have has a method of the right name --
there are too many homonyms possible for that to work reliably. It's
the collection of methods under a trait name that makes this useful.
-- c
More information about the Pdx-pm-list
mailing list