Using setters during initialization

6 views
Skip to first unread message

Nickolay Platonov

unread,
Dec 3, 2010, 8:21:43 AM12/3/10
to joose-js
[16:01] <SamuraiJack> I'm starting to think, that initial values (supplied to constructor) should *not* go through setters..

[16:03] <SamuraiJack> in particular that means that triggers won't be called during initialization

[16:03] <SamuraiJack> and in general, any logic from custom setters will be skipped

[16:11] <SamuraiJack> the reason is that since the order of attributes initialization is undefined

[16:11] <SamuraiJack> initialization should be as much side-effects free as possible (pure code)

[16:11] <SamuraiJack> and custom setters usually rely on some other attributes anyway


[16:01] <SamuraiJack> any comments?



Sir Robert Burbridge

unread,
Dec 3, 2010, 10:40:53 AM12/3/10
to joos...@googlegroups.com
See http://search.cpan.org/~drolsky/Moose-1.21/lib/Moose/Manual/Attributes.pod#Initializer

There's an "initializer" that allows you to manipulate initial values.  Behold, Moose's approach:

$ ls
total 8.0K

-rw-r--r-- 1 231 Dec  3 10:37 Foo.pm
-rwxr-xr-x 1  97 Dec  3 10:37 foo_runner.pl*
$ cat foo_runner.pl
#!/usr/bin/perl
use strict;
use warnings;

use Foo;

my $foo = Foo->new(funk => 'punk');

exit;

$ cat Foo.pm
package Foo;
use Moose;

has funk => (
   isa         => 'Str',
   is          => 'rw',
   initializer => '_init_funk',
);

before funk => sub {
   print "About to set funk!\n";
};

sub _init_funk {
   print "Get funky!\n";
}

1;

$ ./foo_runner.pl
Get funky!
$

I think this is The Correct Approach (hey, to each my own).

-Sir



--
You received this message because you are subscribed to the Google Groups "Joose" group.
To post to this group, send email to joos...@googlegroups.com.
To unsubscribe from this group, send email to joose-js+u...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/joose-js?hl=en.

Nickolay Platonov

unread,
Dec 3, 2010, 12:01:33 PM12/3/10
to joos...@googlegroups.com
Yes, Moose either doesn't use accessors for initial values, for the same reasons (quick chat on #moose confirmed that).

As about initializers - there are "builders": http://joose.github.com/Joose/doc/html/Joose/Manual/Attributes.html#defaultvalue

("initializers" term is reserved for pre-defined initializing functions).
Reply all
Reply to author
Forward
0 new messages