[Pdx-pm] Poll: traits

chromatic chromatic at wgz.org
Sat Nov 19 12:57:22 PST 2005

On Sat, 2005-11-19 at 12:40 -0800, Marvin Humphrey wrote:

> That sounds like a Java interface.

Gah, I *hate* Java interfaces.  The designers saw a problem and
completely failed to solve it.

The problem is that not all important behavior in a system fits nicely
into a class hierarchy.  To borrow a phrase from aspect-oriented
programming, you sometimes have cross-cutting concerns.  That is, if you
want to serialize an object, you don't necessarily want to have to
inherit from a Serialize class.  In a single-inheritance scheme like
Java supposedly has, there goes your code reuse.  In a closed-class
scheme like Java has also, you can't just stick the appropriate methods
in the Object class either.  Pragmatically, you may not *want* all
classes to have serializeable objects!

Java's "solution" was to allow multiple inheritance without actually
allowing multiple inheritance.  That is, you can inherit from only one
class, but you can "inherit" from multiple interfaces that don't share
the same namespace as classes, don't provide any behavior, and have a
completely different querying mechanism.

If you want to write an object that proxies for another object and be
able to use your type system to check that you're performing the correct
operations on the correct objects, you have to modify the first object's
class to create an interface, modify every piece of code that wants to
perform an operation on objects of that class to check for that
interface instead of the class, and then write the proxy.  Yippee.

Instead, traits allow you to define a bundle of named behavior.  If you
don't implement those methods on your own but perform the trait, you get
the trait's implementations.  Code reuse is good.  If you do implement
those methods on your own but do the trait, you don't get the trait's
implementations, but you do tell the system that everything that wants
to perform an operation on something that performs that trait can safely
use your objects because they do the right thing.

Better (I hope Curtis's code does this, because it's immensely
important), if you have a class, you automatically get a trait with the
same name as that class with the same methods of that class and you can
reimplement everything that class does and say that you do the trait and
then everything that asks trait-like questions about objects of your
class will do the right thing even if they always expected to receive
objects of the other class.

That is, traits and roles let you worry about whether an object does
what you expect it does, not how it does it nor where it fits into an
inheritance hierarchy.

This is as it should be.

-- c

More information about the Pdx-pm-list mailing list