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.

TO DO

Being the first release of this module, there is always something left undone. I consider the 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:

Tests, Tests, Tests

At this point, there are only 37 automated tests included in this release. Of course with something as complex as Traits, this is nowhere near enough. But being that Traits are complex, creating tests for it is not easy. I invite anyone interested in helping this module along to help write tests or even just help plan them.

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_little@yahoo.com>

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

COPYRIGHT AND LICENSE

Copyright 2004 by Stevan Little.

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