Perl TM Tutorial: Traits Good, Classes Bad (Part V)
(Followup to part IV)
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.
my $tm = new TM::Materialized::AsTMa
(file => 'old_testament.atm')->sync_in;
And now we attach the trait to it:
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:
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:
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:
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.
Work supported by the Austrian Research Centers.