Skip to content

Commit

Permalink
Improve classtut example again
Browse files Browse the repository at this point in the history
* Bring back private attributes (BUILD submethod needed to bind them properly).
* Add some doc explaining the BUILD usage in the example.
  • Loading branch information
kanatohodets committed Jun 20, 2014
1 parent e115f9f commit d99e1cf
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions lib/Language/classtut.pod
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,24 @@ result is interesting and, at times, useful.
=begin code
class Task {
has &.callback;
has Task @.dependencies;
has &!callback;
has Task @!dependencies;
has Bool $.done;
method new(&callback, *@dependencies) {
return self.bless(:&callback, :@dependencies);
}
submethod BUILD(:&!callback, :@!dependencies) { }
method add-dependency(Task $dependency) {
push @!dependencies, $dependency;
}
method perform() {
unless $!done {
.perform() for @.dependencies;
&.callback.();
.perform() for @!dependencies;
&!callback();
$!done = True;
}
}
Expand Down Expand Up @@ -253,6 +255,21 @@ into the C<@dependencies> slurpy array and passes them as named parameters to
C<bless> (note that C<:&callback> uses the name of the variable--minus the
sigil--as the name of the parameter).
X<|BUILD>
Private attributes really are private. This means that C<bless> is not allowed
to bind things to C<&!callback> and C<@!dependencies> directly. To do this, we
override the C<BUILD> submethod, which is called on the brand new object by
C<bless>:
submethod BUILD(:&!callback, :@!dependencies) { }
Since C<BUILD> runs in the context of the newly created C<Task> object, it is
allowed to manipulate those private attributes. The trick here is that the
private attributes (C<&!callback> and C<&!dependencies>) are being used as the
bind targets for C<BUILD>'s parameters. Zero-boilerplate initialization! See
L<objects|/language/objects#Object Construction> for more information.
=head1 Consuming our class
After creating a class, you can create instances of the class. Declaring a
Expand Down

0 comments on commit d99e1cf

Please sign in to comment.