1 package Moose::Cookbook::Basics::BinaryTree_BuilderAndLazyBuild;
3 # ABSTRACT: Builder methods and lazy_build
15 has 'node' => (is => 'rw', isa => 'Any');
20 predicate => 'has_parent',
27 predicate => 'has_left',
29 builder => '_build_child_tree',
35 predicate => 'has_right',
37 builder => '_build_child_tree',
40 before 'right', 'left' => sub {
41 my ($self, $tree) = @_;
42 $tree->parent($self) if defined $tree;
45 sub _build_child_tree {
48 return BinaryTree->new( parent => $self );
53 If you've already read
54 L<Moose::Cookbook::Basics::BinaryTree_AttributeFeatures>, then this example
55 should look very familiar. In fact, all we've done here is replace the
56 attribute's C<default> parameter with a C<builder>.
58 In this particular case, the C<default> and C<builder> options act in
59 exactly the same way. When the C<left> or C<right> attribute is read,
60 Moose calls the builder method to initialize the attribute.
62 Note that Moose calls the builder method I<on the object which has the
63 attribute>. Here's an example:
65 my $tree = BinaryTree->new();
67 my $left = $tree->left();
69 When C<< $tree->left() >> is called, Moose calls C<<
70 $tree->_build_child_tree() >> in order to populate the C<left>
71 attribute. If we had passed C<left> to the original constructor, the
72 builder would not be called.
74 There are some differences between C<default> and C<builder>. Notably,
75 a builder is subclassable, and can be composed from a role. See
76 L<Moose::Manual::Attributes> for more details.
78 =head2 The lazy_build shortcut
80 The C<lazy_build> attribute option can be used as sugar to specify
81 a whole set of attribute options at once:
89 This is a shorthand for:
96 builder => '_build_animal',
97 predicate => 'has_animal',
98 clearer => 'clear_animal',
101 If your attribute starts with an underscore, Moose is smart and will
102 do the right thing with the C<predicate> and C<clearer>, making them
103 both start with an underscore. The C<builder> method I<always> starts
106 You can read more about C<lazy_build> in L<Moose::Meta::Attribute>
110 The C<builder> option is a more OO-friendly version of the C<default>
111 functionality. It also separates the default-generating code into a
112 well-defined method. Sprinkling your attribute definitions with
113 anonymous subroutines can be quite ugly and hard to follow.