Why does the Moose builder take string value?

Moose :: Manual :: Attributes states:

As an alternative to using the routine reference [default], you can instead create a build method for your attribute: ... This has several advantages. First, it moves a piece of code into its own named method, which improves the readability and organization of the code.

So your attribute can define a default value:

has attr => ( is => 'ro', builder => 'subroutine' ); sub subroutine { # figure out and return default value } 

I do not understand why this should be separate from default. Could you just pass the link to the named routine?

 has attr => ( is => 'ro', default => \&subroutine ); 

And would it not be a more complicated programming practice, since you should not accidentally refer to a routine that does not exist? You are referring to a method with a logical link instead of a symbolic link.

+7
perl moose
source share
3 answers

When the builder is called, this happens:

 $object->$builder 

If the builder is a string (say build_attr ), then users can write their own build_attr method in a subclass and it will be called. This makes the default value extensible using a simple named method.

If it is a reference to a subroutine, the link is executed in the source class package, which means that it cannot be redefined in the same way.

+14
source share

This is not a "symbolic" link. The constructor is the name of the method. This means that it is inherited and can be composed of a role. If you pass a subprogram link, this link must exist in one package (or be fully qualified).

I am sure I will explain this in the manual. Dont clear?

+10
source share

subclasses.

Builder indicates the name of the method to call, therefore

 package Something; use Moose; extends 'YourClass'; sub subroutine { <some other default> } 

will have the "Something ::" subroutine called for the creator of the "subroutine", whereas if you were using the subref style, the "YourClass ::" subroutine would be called instead because you were directly referring to the subroutine, and not go to it shipping method.

+7
source share

All Articles