Tag: Class::Method::Modifiers

  • Multiple ways to inheritance in Perl

    Multiple ways to inheritance in Perl

    Inspired by my par­ents com­ing to vis­it at the end of the week, I thought I’d write about how Perl class­es can have ​“par­ents” as well, from which they inher­it meth­ods. Although it might seem on the sur­face as though there’s more than one way to do it, these tech­niques all share the same under­ly­ing mechanism.

    Where it all BEGINs: @ISA

    Perl class­es are just repur­posed packages, i.e., a name­space for vari­ables and sub­rou­tines. The two key dif­fer­ences are:

    If you want­ed to do every­thing by hand at the low­est lev­el, you could make a sub­class at com­pile time like this:

    package Local::MyChildClass;
    BEGIN { # don't do this:
        require Local::MyParentClass;
        push @ISA, 'Local::MyParentClass';
    }

    Don’t do that though, because we have…

    baseand parent

    In 1997 Perl 5.004_04 intro­ducedthe baseprag­ma (back when Perl used that kind of ver­sion­ing scheme; in these days of seman­tic ver­sion­ingwe’d call it ver­sion 5.4.4). It does the above BEGINblockin a sin­gle line:

    use base 'Local::MyParentClass'; # don't do this unless you're also using fields

    You might see use basein old­er code espe­cial­ly if it’s also using the fieldsprag­ma. However, Perl devel­op­ers dis­cour­ageboth as the for­mer silences cer­tain mod­ule load­ing errorswhile the lat­ter is at odds with the object-​oriented pro­gram­ming prin­ci­ple of encap­su­la­tion.

    So use parentinstead, which Perl has includ­ed since ver­sion 5.10.1in 2009:

    use parent 'Local::MyParentClass';

    A cou­ple of years ago my Newfold Digitalcol­league David Oswaldcre­at­ed a fork of par­ent called parent::versionedthat sup­ports spec­i­fy­ing the low­est ver­sion for super­class­es. You call it like this:

    use parent::versioned ['Local::MyParentClass' => 1.23];

    Within an OO system

    There are dozens of object-​oriented pro­gram­ming sys­temson CPANthat pro­vide syn­tac­tic sug­arand extra fea­tures to Perl’s min­i­mal but flex­i­ble basics. Two of the more pop­u­lar ones, Mooseand Moo, offer an extendskey­word that you should use instead of use parentso that your sub­class­es may take advan­tage of their features:

    package Local::MyChildClass;
    use Moo;
    extends 'Local::MyParentClass';

    Moose can also spec­i­fy a required super­class version:

    package Local::MyChildClass;
    use Moose;
    extends 'Local::MyParentClass' => {-version => 1.23};

    Also, use the MooseX::NonMoosemod­ule when extend­ing non-​Moose class­es, again so you get Moose fea­tures even though your meth­ods are com­ing from some­where else:

    package Local::MyMooseClass;
    use Moose;
    use MooseX::NonMoose;
    extends 'Local::MyPlainParentClass';

    The exper­i­men­tal Object::Padmod­ule spec­i­fies a sin­gle super­class while defin­ing the class name with an option­al ver­sion. Per the author’s sug­gest­ed file lay­out, includ­ing a required min­i­mum ver­sion, it would look like:

    use Object::Pad 0.41;
    package Local::MyChildClass;
    class Local::MyChildClass isa Local::MyParentClass 1.23;

    Object::Pad and Corinna, its inspi­ra­tion, are works in progress so this syn­tax isn’t set in stone. The latter’s design­er Curtis ​“Ovid” Poe blogged ear­li­er this weekabout con­sid­er­ing a more self-​consistent syntax.

    Multiple inheritancevs. roles

    To quote the Perl doc­u­men­ta­tion, ​“mul­ti­ple inher­i­tance often indi­cates a design prob­lem, but Perl always gives you enough rope to hang your­self with if you ask for it.” All the tech­niques described above except for Object::Pad sup­port mul­ti­ple inher­i­tance by spec­i­fy­ing a list of super­class­es. For example:

    package Local::MyChildClass;
    use parent qw(Local::MyParentClass1 Local::MyParentClass2);

    If you’re using roles instead of or on top of super­class­es (I’ve seen both sit­u­a­tions) and your OO sys­tem doesn’t sup­port them on its own, you can use the Role::Tiny mod­ule, first by describ­ing your role in one pack­age and then con­sum­ing it in another:

    package Local::DoesSomething;
    use Role::Tiny;
    
    ...
    
    1;
    package Local::MyConsumer;
    use Role::Tiny::With;
    with 'Local::DoesSomething';
    
    ...
    
    1;

    Moo::Roleuses Role::Tiny under the hood and Moo can com­pose roles from either. The syn­tax for both Moo and Moose is similar:

    package Local::DoesSomething;
    use Moo::Role; # or "use Moose::Role;"
    
    ...
    
    1;
    package Local::MyConsumer;
    use Moo; # or "use Moose;"
    with 'Local::DoesSomething';
    
    ...
    
    1;

    Object::Pad spec­i­fies roles with the rolekey­word, and both class­es and roles use doesto con­sume them:

    use Object::Pad 0.56;
    package Local::DoesSomething;
    role Local::DoesSomething does Local::DoesSomethingElse;
    
    ...
    
    1;
    use Object::Pad 0.56;
    package Local::MyConsumer;
    class Local::MyConsumer does Local::DoesSomething;
    
    ...
    
    1;

    The pre­vi­ous caveatabout pos­si­ble changes to this syn­tax applies.

    Like parent, (sort of) like child

    Of course, the whole point of inher­i­tance or role con­sump­tion is so your child or con­sumer class can reuse func­tions and meth­ods. Each of the tech­niques above has its ways of over­rid­ing that code, from the Perl built-​in SUPERpseudo-​classto Moose’s overrideand superkey­words, to Moose’sand Moo’smethod mod­i­fiers. (You can use the lat­ter out­side of Moo since it’s pro­vid­ed by Class::Method::Modifiers.)

    I’ve writ­ten about choos­ing between over­rid­ingand mod­i­fy­ing meth­odsbefore, and when it comes to Moose and Moo code I’m now on the side of using the aroundmethod mod­i­fi­erif a method needs to call an inher­it­ed or con­sumed method of the same name. Object::Pad doesn’t have method mod­i­fiers (yet), so classes that use it will have to sat­is­fy them­selves with SUPERin their methods with an :overrideattribute that will throw an error if a par­ent doesn’t also pro­vide the same method.

    The Parent Wrap

    In the end, your choice of Perl OO sys­temwill deter­mine how (or whether) you han­dle inher­i­tance and may even be a decid­ing fac­tor. Which would you choose? And more impor­tant­ly, have I made my par­ents proud with this post?

  • Cutting the fat: Lightweight Perl OO modules

    Cutting the fat: Lightweight Perl OO modules

    This blog has devot­ed a fair amount of atten­tion to the pop­u­lar and mul­ti­fac­eted object-​oriented sys­tem Mooseand its light­weight sub­set Moo. I’ve also cov­ered Object::Pad, the test­bed of con­cepts and syn­tax for Corinna, the pro­posednext-​generation Perl core OO sys­tem. But what if your project is too memory‑, performance‑, or dependency-​constrained for these options?

    It turns out that CPANhas a rich his­to­ry of lighter-​weight OO mod­ules to meet many dif­fer­ent needs. If you can live with their trade-​offs, they’re worth inves­ti­gat­ing instead of rolling your own lay­er over Perl’s OO. Here are a few.

    Class::Struct

    Class::Struct​’s main claim to fame is its inclu­sion in the stan­dard Perl dis­tri­b­u­tion, so there’s no need to install depen­den­cies from CPAN. It pro­vides a syn­tax for defin­ing class­es as C‑style structsat either com­pile timeor run­time. (There’s no speed advan­tage to the for­mer; it just means that your class will be built as if you had writ­ten the acces­sors your­self as subs.) Here’s an example:

    #!/usr/bin/env perl
    
    use v5.24; # for strict, say, and postfix dereferencing
    use warnings;
    
    package Local::MyClass;
    use Class::Struct (
        foo => '$',
        bar => '@',
        baz => '%',
    );
    
    package main;
    
    my $obj = Local::MyClass->new(
        foo => 'hello',
        bar => [1, 2, 3],
        baz => { name => 'Mark'},
    );
    
    say $obj->foo, ' ', $obj->baz('name');
    say join ',', $obj->bar->@*;
    
    # replace the name element of baz
    $obj->baz(name => 'Sharon');
    
    # replace the second element of bar
    $obj->bar(1, 'replaced');
    say $obj->foo, ' ', $obj->baz('name');
    say join ',', $obj->bar->@*;

    And here’s the output:

    hello Mark
    1,2,3
    hello Sharon
    1,replaced,3

    Note that Class::Struct sup­ports acces­sors for scalar, array, and hash types, as well as oth­er class­es (not demon­strat­ed). Consult the module’s doc­u­men­ta­tionfor the dif­fer­ent ways to define and retrieve them.

    Class::Accessor

    Class::Accessordoes one thing: it makes acces­sors and muta­tors (also known as get­ters and set­ters) for fields in your class. Okay, it actu­al­ly does anoth­er thing: it pro­vides your class with a new method to ini­tial­ize those fields. Those acces­sors can be read-​write, read-​only, or write-​only. (Why would you want write-​only acces­sors?) You can define any of them using either its his­tor­i­cal class meth­ods or a Moose-​like attribute syn­tax.

    If you’re try­ing to squeeze every bit of per­for­mance out of your code and can sac­ri­fice a lit­tle flex­i­bil­i­ty in alter­ing acces­sor behav­ior, you can opt for Class::Accessor::Fastor Class::Accessor::Faster. The for­mer still uses hash ref­er­ences under the hood to rep­re­sent objects and the lat­ter uses array ref­er­ences. The main Class::Accessor doc­u­men­ta­tion con­tains an effi­cien­cy com­par­i­son of the threefor your edification.

    Here’s an exam­ple script using Class::Accessor::Faster and the Moose-​like syntax:

    #!/usr/bin/env perl
    
    use v5.12; # for strict and say
    use warnings;
    
    package Local::MyClass;
    use Class::Accessor::Faster 'moose-like';
    
    has readwrite => (is => 'rw');
    has readonly  => (is => 'ro');
    
    package main;
    
    my $obj = Local::MyClass->new( { # must be a hash reference
        readwrite => 'hello',
        readonly  => 'world',
    } );
    
    say $obj->readwrite, ' ', $obj->readonly;
    $obj->readwrite('greetings');
    say $obj->readwrite, ' ', $obj->readonly;
    
    # throws an error
    $obj->readonly('Cleveland');

    And here is its output:

    hello world
    greetings world
    'main' cannot alter the value of 'readonly' on objects of class 'Local::MyClass' at ./caf.pl line 24.

    Class::Tiny

    Class::Tinyboth does less and more than Class::Accessor. All of its gen­er­at­ed acces­sors are read-​write, but you can also give their attrib­ut­es lazy defaults. Its gen­er­at­ed con­struc­tor takes argu­ments via either a Class::Accessor-style hash ref­er­ence or a plain list of key/​value pairs, so that’s a lit­tle more con­ve­nient. It also sup­ports Moose-​style BUILDARGS, BUILD, and DEMOLISHmeth­ods for argu­ment adjust­ment, val­i­da­tion, and object cleanup, respectively.

    It’s a toss-​up as to which of the pre­vi­ous two is ​“bet­ter.” You’ll have to exam­ine their respec­tive fea­tures and deter­mine which ones map to your needs.

    Here’s an exam­ple script that shows a few of Class::Tiny’s unique features:

    #!/usr/bin/env perl
    
    use v5.12; # for strict and say
    use warnings;
    
    package Local::MyClass;
    use Class::Tiny qw<foo bar>,
    {
        baz       => 'default baz',
        timestamp => sub { time },
    };
    
    package main;
    
    my $obj = Local::MyClass->new( # plain key-values OK
        foo => 'hello',
        bar => 'world',
    );
    
    say $obj->foo, ' ', $obj->bar;
    say 'Object built on ', scalar localtime $obj->timestamp;
    $obj->foo('greetings');
    $obj->bar('Cleveland');
    say $obj->foo, ' ', $obj->bar;
    say $obj->baz;

    And its output:

    hello world
    Object built on Tue Sep  7 09:00:00 2021
    greetings Cleveland
    default baz

    Object::Tiny

    For an even more min­i­mal­ist approach, con­sid­er Object::Tiny. Its acces­sors are read-​only, it gives you a sim­ple con­struc­tor, and that’s it. Its doc­u­men­ta­tion lists a num­ber of rea­sonswhy it can be supe­ri­or to Class::Accessor, includ­ing low­er mem­o­ry usage and less typ­ing. There’s also a fork called Object::Tiny::RWthat adds read-​write sup­port to its accessors.

    Class::Tiny’s doc­u­men­ta­tion con­tains a fea­ture table com­par­i­sonof it, Object::Tiny, and Class::Accessor. This may help you decide which to use.

    Here’s an exam­ple script:

    #!/usr/bin/env perl
    
    use v5.12; # for strict and say
    use warnings;
    
    package Local::MyClass;
    use Object::Tiny qw<foo bar>;
    
    package main;
    
    my $obj = Local::MyClass->new(
        foo => 'hello',
        bar => 'world',
    );
    
    say $obj->foo, ' ', $obj->bar;
    
    # has no effect unless you use Object::Tiny::RW
    $obj->foo('greetings');
    say $obj->foo, ' ', $obj->bar;

    And its output:

    hello world
    hello world

    Add some speed with XS

    If the above options are still too slow and you don’t mind requir­ing a C com­pil­er to install them, there are vari­ants that use Perl’s XS inter­faceinstead of pure Perl code:

    Roles with Role::Tiny

    If you’re eye­ing Moose and Moo’s sup­port for roles(also known as traits) as an alter­na­tive to inher­i­tance but still want to keep things light with one of the above mod­ules, you’re in luck. The Role::Tinymod­ule lets you com­pose meth­ods into con­sum­ing class­es with Moo-​like syn­tax and will pull in Common Lisp Object System-style method mod­i­fi­ersup­port from Class::Method::Modifiersif you need it. It does mean anoth­er cou­ple of CPAN depen­den­cies, so if that’s a prob­lem in your sit­u­a­tion you’ll just have to live with­out roles.

    Here’s an exam­ple script with a role and a con­sum­ing class that uses Class::Tiny. The role requires that its con­sumers imple­ment a required_method, pro­vides a foomethod that uses it, and a method mod­i­fi­er for bar.

    #!/usr/bin/env perl
    
    use v5.12; # for strict and say
    use warnings;
    
    package Local::MyRole;
    use Role::Tiny;
    
    requires 'required_method';
    
    sub foo {
        my $self = shift;
        say $self->required_method();
    }
    
    before bar => sub {
        warn 'About to call bar...';
    };
    
    package Local::MyClass;
    use Class::Tiny {name => ''};
    use Role::Tiny::With;
    with 'Local::MyRole';
    
    sub bar {
        my ($self, $greeting) = @_;
        say "$greeting ", $self->name;
    }
    
    sub required_method {
        my $self = shift;
        return 'Required by Local::MyRole';
    }
    
    package main;
    
    my $obj = Local::MyClass->new(name => 'Mark');
    $obj->bar('hello');
    
    $obj->name('Sharon');
    $obj->bar('salutations');
    
    $obj->foo();

    And its output:

    About to call bar... at ./rt.pl line 17.
    hello Mark
    About to call bar... at ./rt.pl line 17.
    salutations Sharon
    Required by Local::MyRole

    What’s your favorite?

    There will always be those who insist on writ­ing every­thing long­hand, but mod­ules like these can save a lot of time and typ­ing as well as reduce errors. Do you have a favorite, maybe some­thing I missed? Let me know in the comments.