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 \*(C`toString\*(C' method, which the overloaded "" operator then utilizes. The trait also provides a \*(C`stringValue\*(C' method to the consuming class.

Trait usage

When a class uses a Trait:

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

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 \*(C`TPrintable\*(C' trait, aliasing \*(C`stringValue\*(C' to the method label \*(C`strVal\*(C', and then excluding \*(C`stringValue\*(C'. This is done to avoid a conflict with \*(C`stringValue\*(C' 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. If only a single method needs to be excluded, you may provide the method name without an array.

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

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:

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

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

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

RUNTIME TRAIT APPLICATION

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

The syntax is:

Class::Trait->apply($class_or_instance, @list_of_traits);

Classes

Applying a trait at runtime to a class:

if ($secure) { Class::Trait->apply($class_name, 'TSecureConnection'); } else { warn "Using insecure connections"; Class::Trait->apply($class_name, 'TInsecureConnection'); }

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.

Instances

Applying a trait at runtime to an instance:

if ($secure) { Class::Trait->apply($instance, 'TSecureConnection'); } else { warn "Using insecure connections"; Class::Trait->apply($instance, 'TInsecureConnection'); }

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.

WHEN TO USE TRAITS

For a relatively simple class heirarchy you may need traits. There are, however, several key indicators that traits may be beneficial for you.

  • Duplicated behavior Whenever you've duplicated behavior across unrelated classes.

  • Multiple inheritance Any time you might think about \s-1MI\s0 and it's only for code reuse (in other words, the subclass is not a more specific type of a super class)

  • Interfaces Any time you might want a Java-style interface but you also want an implementation to go with that.

  • Mixins Any time you might want to use mixins (have you ever considered exporting methods?)

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.

  • 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 \*(C`isa\*(C' 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 \*(C`does\*(C' 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 \*(C`does\*(C'. To use \*(C`is\*(C' instead of \*(C`does\*(C', 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 \*(L"action at a distance\*(R" 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.

METHODS

initialize

Class::Trait uses the \s-1INIT\s0 phase of the perl compiler, which will not run under mod_perl or if a package is loaded at runtime with \*(C`require\*(C'. 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 \s-1CAVEAT\s0 section.

rename_does

Note: You probably do not want to use this method. Class::Trait uses \*(C`does()\*(C' to determine if a class can \*(L"do\*(R" a particular trait. However, your package may already have a \*(C`does()\*(C' method defined or you may be migrating from an older version of Class::Trait which uses \*(C`is()\*(C' to perform this function. To rename \*(C`does()\*(C' to something more suitable, you can use this at the top of your code: BEGIN { require Class::Trait; # we do not want to call import() Class::Trait->rename_does($some_other_method_name); }

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.

TRAIT LIBRARY

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.

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 \s-1STDERR\s0 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

This module uses the \s-1INIT\s0 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 \s-1INIT\s0.

Runtime loading

If you load code with \*(C`require\*(C' or \*(C`eval "use Module"\*(C' the result is the same as with mod_perl. It is post-compilation, and the \s-1INIT\s0 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 \*(C`initialize\*(C', 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.

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:

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 \s-1API\s0 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 \s-1DEBUG\s0 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 \s-1CAVEAT\s0) 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 \*(L"subroutine redeined\*(R" 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 \s-1BEGIN\s0 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 \s-1INIT\s0 issue, which will still have the elegance of using \s-1INIT\s0.

Reflection \s-1API\s0

The class Class::Traits::Reflection gives a basic \s-1API\s0 to access to the traits used by a class. Improvements can be made to this \s-1API\s0 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.

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.

PRIVATE METHODS IN TRAITS

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.

package TSomeTrait; use Class::Trait 'base';

my $private = sub { ... };

sub public { my $self = shift; my $data = $self->$private; ... }

ACKNOWLEDGEMENTS

  • Curtis \*(L"Ovid\*(R" Poe Initial idea and code for this module.

  • Nathanael Scharli and the Traits research group. Answering some of my questions.

  • Yuval Kogman Spotting the problem with loading traits with :: in them. Thanks to Curtis \*(L"Ovid\*(R" Poe for bringing it up again, and prompting me to release the fix.

  • Roman Daniel Fixing \s-1SUPER::\s0 handling.

  • Curtis \*(L"Ovid\*(R" Poe The code to change \*(C`is\*(C' to \*(C`does\*(C'.

RELATED TO Class::Trait…

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 \*(L"Traits - A Formal Model\*(R", as well as another paper on statically-typed traits (which is found here : http://www.cs.uchicago.edu/research/publications/techreports/TR-2003-13 <http://www.cs.uchicago.edu/research/publications/techreports/TR-2003-13>).

ERROR MESSAGES

Redefined subroutine warnings

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 \*(L"Subroutine redefined\*(R" warning. To avoid this, explicitly exclude the method:

use Class::Trait TSomeTrait => { exclude => 'foo' };

sub foo {}

Sometimes you will see strange warnings such as:

Subroutine Circle::(== redefined at /usr/lib/perl5/5.8.7/overload.pm at ...

This is because traits can support overloading. To avoid this warning, define your overloaded methods prior to using Class::Trait.

use overload ( '==' => \&equalTo );

use Class::Trait "TCircle" => { exclude => 'equalTo' }, "TColor" => { exclude => 'equalTo' };

BUGS

does

When applying traits at runtime to instances, the following works:

$object->does($some_trait_name);

However, normally we should be able to do the following and get a list of all traits the instance does:

my @does = $object->does;

Currently, this returns no traits. It will be fixed in a future release.

MAINTAINER

Curtis \*(L"Ovid\*(R" Poe, \*(C`<ovid [at] cpan [dot] org>\*(C'

AUTHOR

stevan little, <[email protected]>

The development of this module was initially begun by Curtis \*(L"Ovid\*(R" Poe, <[email protected]>.

COPYRIGHT AND LICENSE

Copyright 2004, 2005 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.