Search code examples
perlmoose

Using sub reference with Moose builder


Moose documentation mentions that builder property for attribute in class definiton should be a string that contains name for function that will be called to build relevant attribute. Simple testing however shows that sub reference works as well:

has 'some_attribute' => (
    is => 'ro',
    lazy => 1,
    builder => sub {
        require SomeModule::Heavy;
        return SomeModule::Heavy->new($_[0]);
    },
);

Did I miss something in docs? Is usage of sub reference officially supported for builder?


Solution

  • Moose manual says:

    You can also provide a subroutine reference for default. This reference will be called as a method on the object. […] As an alternative to using a subroutine reference, you can supply a builder method for your attribute. This has several advantages. First, it moves a chunk of code to its own named method, which improves readability and code organization. Second, because this is a named method, it can be subclassed or provided by a role.

    So, if you use subroutine reference for builder then you lose these advantages. I think subroutine reference works as side effect and has no practical application.