Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moose's attribute vs simple sub?

Tags:

perl

How to decide - what is the recommended way for the next code fragment?

I have a Moose-based module, where some data is a simple HashRef.

It is possible to write - as a Mooseish HashRef, like:

package Some;
has 'data' => (
        isa => 'HashRef',
        builder => '_build_href',
        init_arg => undef,
        lazy => 1,
);

sub _build-href {
        my $href;
        $href = { a=>'a', b=>'b'}; #some code what builds a href
        return $href;
}

vs

sub  data {
        my $href;
        $href = { a=>'a', b=>'b'}; #some code what builds a href
        return $href;
}

What is the difference? I'm asking because when calling:

my $obj = Some->new;
my $href = $obj->data;

In both case I get a correct HashRef. So when is it recommended to use a Moose-ish has construction (which is longer) vs a simple data sub?

PS: probably this question is so simple for an average perl programmer, but please, keep in mind, I'm still only learning perl.

like image 666
jm666 Avatar asked Dec 06 '13 13:12

jm666


1 Answers

If you have an attribute, then whoever is constructing the object can set the hashref in the constructor:

my $obj = Some->new(data => { a => 'c', b => 'd' });

(Though in your example, you've used init_arg => undef which would disable that ability.)

Also, in the case of the attribute, the builder is only run once per object while with a standard method, the method might be called multiple times. If building the hashref is "expensive", that may be an important concern.

Another difference you'll notice is with this:

use Data::Dumper;
my $obj  = Some->new;
$obj->data->{c} = 123;
print Dumper( $obj->data );
like image 139
tobyink Avatar answered Nov 15 '22 03:11

tobyink