NAME

Class::Trait - An implementation of Traits in Perl

SYNOPSIS

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

DESCRIPTION

This document attempts to explain Traits in terms of Perl.

Trait composition

A Trait can be defined as a package containing:

  • A set of methods

  • A hash of overloaded operators mapped to the method labels

  • An array of required method labels

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);
}

1;

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:

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

  • 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.

  • 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.

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.

  • Exclusion

    An array of method labels to exclude from trait.

  • Alias

    A hash of old method labels to new method labels.

  • Summation

    A number of traits can be combined into one.

Exclusion

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

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 new 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.

Summation

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:

  • A union of all non-conflicting methods of all traits.

  • A union of all non-conflicting operators of all traits.

  • A union of all unsatisfied requirements of all traits.

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.

EXPORTS

$TRAITS

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.

is

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->is('TPrintable');

DEBUGGING

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.

CAVEAT

Currently due to our use of the INIT phase of the perl compiler, this will not work with mod_perl. This is on the "TO DO" list though. I am open to any suggestions on how I might go about fixing this.

TO DO

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:

Make this work with mod_perl

Currently due to our use of the INIT phase of the perl compiler, this will not work with mod_perl. My only thought is to use the PerlChildInit handler, but I don't currently have the time to investigate and test this though.

Tests

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/Trait.pm                91.4   58.6   50.0   95.7    6.2    8.9   80.0
/Class/Trait/Base.pm           90.5   50.0    n/a  100.0    n/a    0.1   83.9
/Class/Trait/Config.pm        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.

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.

Tools

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.

SEE ALSO

Class::Trait is an implementation of Traits as described in the the documents found on this site http://www.iam.unibe.ch/~scg/Research/Traits/. In particular the paper "Traits - A Formal Model", as well as another paper on statically-typed traits (which is found here : http://www.cs.uchicago.edu/research/publications/techreports/TR-2003-13).

Class::Trait::Base, Class::Trait::Config, Class::Trait::Reflection

AUTHOR

stevan little, <stevan@iinteractive.com>

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

COPYRIGHT AND LICENSE

Copyright 2004 by Infinity Interactive, Inc.

http://www.iinteractive.com

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