View on
Stevan Little > Class-Trait > Class::Trait



Annotate this POD


Open  1
View/Report Bugs
Module Version: 0.07   Source   Latest Release: Class-Trait-0.31


Class::Trait - An implementation of Traits in Perl


    # 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';            


This document attempts to explain Traits in terms of Perl.

Trait composition

A Trait can be defined as a package containing:

Here is an example of the syntax for a very basic trait:

    package TPrintable;
    use Class::Trait 'base';
    our @REQUIRES = qw(toString);
    our %OVERLOADS = ('""' => toString);
    sub stringValue {
        my ($self) = @_;
        require overload;
        return overload::StrVal($self);

The above example requires the user of the trait to implement a toString method, which the overloaded "" operator then utilizes. The trait also provides a stringValue method to the consuming class.

Trait usage

When a class uses a Trait:

Here is a simple example of the usage of the above trait in a class.

    package MyClass;
    use Class::Trait (
           'TPrintable' => { 
               alias => { "strVal" => "stringValue" }
               exclude => [ "stringValue" ]
    sub stringValue { ... }

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.

Trait operations

When using a trait, the class can make changes to the structure of a trait through the following methods.


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.


When two or more traits are used by a class (or another trait), the traits are first compiled into a composite trait. The resulting composite trait is:

Method conflicts

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.

Operator conflicts

Operator conflicts also result in the exclusion of the operator from the composite trait and the operator then becomes a requirement.

Requirement satisfaction

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.



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.


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.


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:

    require Class::Trait;

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.


Note: You probably do not want to use this method.

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:

    require Class::Trait; # we do not want to call import()

 use Class::Trait 'some_trait';

If you wish to shield your users from seeing this, you can declare any trait with:

 use Class::Trait qw/base performs/; # 'performs' can be any valid method name

You only need to do that in one trait and all traits will pick up the new method name.


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 only 3 traits in there:

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.

Under mod_perl

mod_perl loads all code through some form of eval. It does this after the normal compilation phases are complete. This means we cannot run INIT.

Runtime loading

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.


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
    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
    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:

 ---------------------------- ------ ------ ------ ------ ------ ------ ------
 File                           stmt branch   cond    sub    pod   time  total
 ---------------------------- ------ ------ ------ ------ ------ ------ ------
 /Class/                91.4   58.6   50.0   95.7    6.2    8.9   80.0
 /Class/Trait/           90.5   50.0    n/a  100.0    n/a    0.1   83.9
 /Class/Trait/        100.0    n/a    n/a  100.0  100.0    2.9  100.0
 ---------------------------- ------ ------ ------ ------ ------ ------ ------

Obviously Class::Trait::Config is fine.

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.

Improve mod_perl/INIT phase solution

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.

Reflection API

The class Class::Traits::Reflection gives a basic API to access to the traits used by a class. Improvements can be made to this API as well as the information it supplies.


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.

Trait Lib

In this release I have added some pre-built traits that can be used; TEquality, TComparable, TPrintable. I want to make more of these, it will only help.


Thanks to Curtis "Ovid" Poe for the initial idea and code for this module.
Thanks to the Nathanael Scharli and the Traits research group for answering some of my questions.
Thanks to Yuval Kogman for spotting the problem with loading traits with :: in them. Thanks to Curtis "Ovid" Poe for bringing it up again, and prompting me to release the fix.
Thanks to Roman Daniel for fixing SUPER:: handling.
Thanks to Curtis "Ovid" Poe for the code to change is to does.


Class::Trait is an implementation of Traits as described in the the documents found on this site In particular the paper "Traits - A Formal Model", as well as another paper on statically-typed traits (which is found here :


stevan little, <>

The development of this module was initially begun by Curtis "Ovid" Poe, <>.


Copyright 2004, 2005 by Infinity Interactive, Inc.

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

syntax highlighting: