Class-Tiny icon indicating copy to clipboard operation
Class-Tiny copied to clipboard

Should custom accessors be called for constructor args?

Open dagolden opened this issue 10 years ago • 3 comments

If someone has custom accessors with coercion, currently the accessor won't be called and the coercion thus won't be applied to constructor arguments, which are directly blessed into the object hash.

Should they be called if we can detect custom accessors? If not, we should document a pattern to help people do this, such as in BUILD:

sub BUILD {
    my $self = shift;

    $self->$_( $self->{$_} ) for qw/baz bam/; # coerce custom
}

I worry that there's no way to know that a custom accessor is also a mutator, so leaving it to the end user in BUILD might be the safest thing.

CC: @miyagawa

dagolden avatar Apr 19 '15 16:04 dagolden

This would be nice (it would be Moo compatible), except that as things are currently written, it would prevent read-only custom accessors. They'd have to be generated within Class::Tiny itself.

djerius avatar Oct 11 '16 18:10 djerius

I am also curious about this as part of cxw42/Class-Tiny-ConstrainedAccessor#4. Even letting BUILD know which parameters were indeed constructor parameters would be helpful (always just the actual hashtable keys in the blessed hashref, right?).

cxw42 avatar Mar 20 '19 11:03 cxw42

BUILD does get passed $args as a parameter. This only includes arguments passed to the constructor (technically it returns the hashref produced by BUILDARGS) and not defaults.

tobyink avatar Mar 20 '19 11:03 tobyink