# to turn on debugging (do this before
# any other traits are loaded)
use Class::Trait 'debug';
# nothing happens, but the module is loaded
use Class::Trait;
# loads these two traits and flatten them
# into the current package
use Class::Trait qw(TPrintable TComparable);
# loading a trait and performing some
# trait operations (alias, exclude) first
use Class::Trait (
'TPrintable' => {
alias => { "stringValue" => "strVal" },
exclude => "stringValue",
},
);
# loading two traits and performing
# a trait operation (exclude) on one
# module to avoid method conflicts
use Class::Trait
'TComparable' => {
# exclude the basic equality method
# from TComparable and use the ones
# in TEquality instead.
exclude => [ "notEqualTo", "equalTo" ]
},
'TEquality' # <- use equalTo and notEqualTo from here
);
# when building a trait, you need it
# to inherit from the trait meta/base-class
# so do this ...
use Class::Trait 'base';

All requirements of the traits (or composite trait) must be meet either by the class itself or by one of its base classes.

Flattening

All the non-conflicting trait (or composite trait) methods are flattened into the class, meaning an entry is created directly in the class's symbol table and aliased to the original trait method. Only methods defined in the trait are used. Subroutines imported into the trait are not used.

Conflicts

If a method label in a class conflicts with a method label in the trait (or composite trait), the class method is chosen and the trait method is discarded. This only applies to methods defined directly in the class's symbol table, methods inherited from a base class are overridden by the trait method.

The above example would use the TPrintable trait, aliasing stringValue to the method label strVal, and then excluding stringValue. This is done to avoid a conflict with stringValue method implemented in the class that uses the trait.

This excludes a method from inclusion in the class which is using the trait. It does however cause the method to be added to the traits required methods. This is done because it is possible that other methods within the trait rely on the excluded method, and therefore it must be implemented somewhere in order for the other method to work.

Aliasing is not renaming or redefining, it does not remove the old method, but instead just introduces another label for that method. The old method label can be overridden or excluded without affecting the new method label.

One special note is that aliasing does move any entry in the overloaded operators to use the new method name, rather than the old method name. This is done since many times aliasing is used in conjunction with exclusion to pre-resolve conflicts. This avoids the orphaning of the operator.

Method equality if determined by two conditions, the first being method label string equality, the second being the hex address of the code reference (found by stringifying the subroutine reference).

If a method in one of the traits is deemed to be in conflict with a method in another trait, the result is the exclusion of that method from the composite trait. The method label is then added to the requirements array for the composite trait.

Method conflict can be avoided by using exclusion or a combination of aliasing and exclusion.

One trait may satisfy the requirements of another trait when they are combined into a composite trait. This results in the removal of the requirement from the requirements array in the composite trait.

As of Class::Trait version 0.20, you can now apply traits at runtime to both classes and instances by using the apply() method. Applying a trait at runtime is similar to using the trait as a mixin because existing methods will be overwritten.

Now all instances of $class_name will have the methods provided by the trait applied. If the trait applied at runtime provides methods already defined in $class_name, the $class_name methods will be silently redefined with the trait's methods.

When applying a trait (or set of traits) to an instance of a class, only that instance gets the new methods. If you want numerous instances to receive the new methods, either apply the trait to all instances or consider applying it to the class.

Note that the instance is blessed into a new, anonymous class and it's this class which contains the new methods.

While not really exported, Class::Trait leaves the actual Class::Trait::Config object applied to the package stored as scalar in the package variable at $TRAITS.

does

Class::Trait will export this method into any object which uses traits. By calling this method you can query the kind of traits the object has implemented. The method works much like the perl isa method in that it performs a depth-first search of the traits hierarchy and returns true (1) if the object implements the trait, and false (0) otherwise.

$my_object_with_traits->does('TPrintable');

Calling does without arguments will return all traits an ojbect does.

is

Class::Trait used to export this method to any object which uses traits, but it was found to conflict with Test::More::is. The recommended way is to use does.

To use is instead of does, one trait must use the following syntax for inheritance:

use Class::Trait qw/base is/;

Instead of:

use Class::Trait 'base';

It is recommended that all traits use this syntax if necessary as the mysterious "action at a distance" of renaming this method can be confusing.

As an alternative, you can also simply use the following in any code which uses traits:

BEGIN {
require Class::Trait;
Class::Trait->rename_does('is');
}

This is generally not recommended in test suites as Test::More::is() conflicts with this method.

Class::Trait uses the INIT phase of the perl compiler, which will not run under mod_perl or if a package is loaded at runtime with require. In order to insure that all traits a properly verified, this method must be called. However, you may still use Class::Trait without doing this, for more details see the CAVEAT section.

Class::Trait uses does() to determine if a class can "do" a particular trait. However, your package may already have a does() method defined or you may be migrating from an older version of Class::Trait which uses is() to perform this function. To rename does() to something more suitable, you can use this at the top of your code:

I have moved some of the traits in the test suite to be used outside of this, and put them in what I am calling the trait library. This trait library will hopefully become a rich set of base level traits to use when composing your own traits. Currently there are the following pre-defined traits.

TPrintable

TEquality

TComparable

These can be loaded as normal traits would be loaded, Class::Trait will know where to find them. For more information about them, see their own documenation.

Class::Trait is really an experimental module. It is not ready yet to be used seriously in production systems. That said, about half of the code in this module is dedicated to formatting and printing out debug statements to STDERR when the debug flag is turned on.

use Class::Trait 'debug';

The debug statements prints out pretty much every action taken during the traits compilation process and on occasion dump out Data::Dumper output of trait structures. If you are at all interested in traits or in this module, I recommend doing this, it will give you lots of insight as to what is going on behind the scences.

This module uses the INIT phase of the perl compiler to do a final check of the of the traits. Mostly it checkes that the traits requirements are fufilled and that your class is safe to use. This presents a problem in two specific cases.

If you load code with require or eval "use Module" the result is the same as with mod_perl. It is post-compilation, and the INIT phase cannot be run.

However, this does not mean you cannot use Class::Trait in these two scenarios. Class::Trait will just not check its requirements, these routines will simply throw an error if called.

The best way to avoid this is to call the class method initialize, after you have loaded all your classes which utilize traits, or after you specifically load a class with traits at runtime.

Class::Trait->initialize();

This will result in the final checking over of your classes and traits, and throw an exception if there is a problem.

Some people may not object to this not-so-strict behavior, the smalltalk implementation of traits, written by the authors of the original papers behaves in a similar way. Here is a quote from a discussion I had with Nathanael Scharli, about the Smalltalk versions behavior:

Well, in Squeak (as in the other Smalltalk dialects), the difference
between runtime and compile time is not as clear as in most other
programming languages. The reason for this is that programming in
Smalltalk is very interactive and there is no explicit compile phase.
This means that whenever a Smalltalk programmer adds or modifies a method,
it gets immediately (and automatically) compiled and installed in the
class. (Since Smalltalk is not statically typed, there are no type checks
performed at compile time, and this is why compiling a method simply means
creating and installing the byte-code of that method).
However, I actually like if the programmer gets as much static information
bout the code as possible. Therefore, my implementation automaticelly
checks the open requirements whenever a method gets
added/removed/modified. This means that in my implementation, the
programmer gets interactive feedback about which requirements are still to
be satisfied while he is composing the traits together. In particular, I
also indicate when all the requirements of a class/trait are fulfilled. In
case of classes, this means for the programmer that it is now possible to
actually use the class without running into open requirements.
However, according to the Smalltalk tradition, I do not prevent a
programmer from instantiating a class that still has open requirements.
(This can be useful if a programmer wants to test a certain functionality
of a class before it is actually complete). Of course, there is then
always the risk that there will be a runtime error because of an
unsatisfied requirement.
As a summary, I would say that my implementation of traits keeps track of
the requirements at compile time. However, if an incomplete class (i.e., a
class with open requirements) is instantiated, unfulfilled requirements
result in a runtime error when they are called.

I consider this implementation of Traits to be pretty much feature complete in terms of the description found in the papers. Of course improvements can always be made, below is a list of items on my to do list:

I have revamped the test suite alot this time around. But it could always use more. Currently we have 158 tests in the suite. I ran it through Devel::Cover and found that the coverage is pretty good, but can use some help:

To start with Class::Trait::Reflection is not even tested at all. I am not totally happy with this API yet, so I am avoiding doing this for now.

The pod coverage is really low in Class::Trait since virtually none of the methods are documented (as they are not public and have no need to be documented). The branch coverage is low too because of all the debug statements that are not getting execute (since we do not have DEBUG on).

The branch coverage in Class::Trait::Base is somwhat difficult. Those are mostly rare error conditions and edge cases, none the less I would still like to test them.

Mostly what remains that I would like to test is the error cases. I need to test that Class::Traits blows up in the places I expect it to.

Currently the work around for the mod_perl/INIT phase issue (see CAVEAT) is to just let the unfufilled requirement routines fail normally with perl. Maybe I am a control freak, but I would like to be able to make these unfufilled methods throw my own exceptions instead. My solution was to make a bunch of stub routines for all the requirements. The problem is that I get a bunch of "subroutine redeined" warnings coming up when the local method definitions are installed by perl normally.

Also, since we are installing our methods and our overloads into the class in the BEGIN phase now, it is possible that we will get subroutine redefinition errors if there is a local implementation of a method or operator. This is somewhat rare, so I am not as concerned about that now.

Ideally I would like to find a way around the INIT issue, which will still have the elegance of using INIT.

Being a relatively new concept, Traits can be difficult to digest and understand. The original papers does a pretty good job, but even they stress the usefulness of tools to help in the development and understanding of Traits. The 'debug' setting of Class::Trait gives a glut of information on every step of the process, but is only useful to a point. A Traits 'browser' is something I have been toying with, both as a command line tool and a Tk based tool.

Sometimes a trait will want to define private methods that only it can see. Any subroutine imported into the trait from outside of the trait will automatically be excluded. However, a trait can define private methods by using anonymous subroutines.

If a class using a trait has a method which the trait defines, the class's method is assumed to be the correct method. However, you should get a "Subroutine redefined" warning. To avoid this, explicitly exclude the method: