Perl TM Tutorial: Traits Good, Classes Bad (Part V)

(Followup to part IV)

When you browse through the list of packages you will notice a number of traits. A trait is effectively additional behaviour for your classes, or your objects.

In the context of Topic Maps I have used traits to extend the behaviour of the base class TM. One typical example would be TM::Graph which extends the basic behaviour of the base class by interpreting a topic map as a graph. Another example is TM::Tree which adds functionality to project trees into a topic map (typical pedigree stuff), and also TM::Bulk adds more methods.

To subclass, or not to subclass

To use one of these traits you can either create a new class where you mix the base class with the trait; or if you prefer things loose and fast, you can also attach a trait directly to a topic map object you already have.

While this works with any map, let us quickly create a map from an AsTMa file (attached):

use TM::Materialized::AsTMa;
my $tm = new TM::Materialized::AsTMa
             (file => 'old_testament.atm')->sync_in;

And now we attach the trait to it:

Class::Trait->apply ( $tm => 'TM::Graph' );

Done. Only that object has that behaviour.

If for some reason you also want the map to have tree methods, you can throw this in, too:

Class::Trait->apply ( $tm => 'TM::Tree' );

Business as usual

Right after a trait attachment, you can use the provided functionality as if it were always native in the class. The following would use TM::Tree to dump out the pedigree starting with a guy called Adam in a strangely violent book:

use Data::Dumper;
print Dumper $tm->tree (lid   => 'adam',
                        type  => 'begets',
                        arole => 'parent',
                        brole => 'child' );

And the following method from TM::Graph would print out all islands, i.e. topics which are somehow connected via assertions:

print Dumper $tm->clusters;


Traits are a great way to keep the functionality organized without being bogged down by an unmanageable zoo of classes. I have also used traits to model IO behavior of maps, i.e. how and when they synchronize their content with an external resource. More about this later.

Good Night, and Good Luck

Work supported by the Austrian Research Centers.

old_testament.atm453 bytes
Posted In