WTF is a trait?

Tom Phoenix rootbeer at redcat.com
Sat Sep 3 17:43:18 UTC 2005


On 9/3/05, Alan Grimes <alangrimes at starpower.net> wrote:

> The first issue is that I have hardly a clue as to what is meant by a
> "trait". It was never mentioned in any of the classes I took or in any
> of the textbooks I have read on my own time.

They're a relatively new concept in Smalltalk. The general idea (and
somebody correct me if I'm wrong) is that a trait can become an
ancestor to a class without being a class itself. That is, a trait is
a dictionary of related methods; you may use most or all of those
methods without further modification in programming a class.

For a real-world-ish example, if I were making an Automobile object, I
would need to include methods to allow a key to open or start the
Automobile. Similarly, if I were making an Apartment or a Locker, I
would need methods to allow a key. But instead of making all of those
inherit from LockableObject, I could have a trait for Lockability. Any
object with that trait has methods understanding, say, that the wrong
key doesn't work in the lock.

So, why not make all of those inherit from LockableObject? Because the
Automobile inherits from Vehicle, which may or not be a
LockableObject. The others don't have lockable ancestors either. We
don't want to make all of the ancestor classes lockable, and we don't
want to duplicate the lockability code in each of the classes that
needs it.

In other words, when traits are available, you may inherit some
methods from ancestor classes, and some from ancestor traits. The
traits allow you to share ancestor methods without having to have a
common ancestor with those methods.

Hope this helps!

--Tom Phoenix



More information about the Squeak-dev mailing list