Perl-Apollo / Corinna

Corinna - Bring Modern OO to the Core of Perl
Artistic License 2.0
157 stars 19 forks source link

[Phasers] Where is the equivalent of BUILDARGS? #33

Closed robrwo closed 2 years ago

robrwo commented 3 years ago

Moo(se) have BUILDARGS which I have found to be very useful. A common use case:

my $x = Foo->new( a => ..., b => ..., c => ... );
my $y = Bar->new( a => $x->a, b => $x->b, c => $x->c );

using a BUILDARGS method allows us to add constructor-only slots:

my $y = Bar->new( from_foo => $x );

or even

my $y = Bar->new( $x );

(Requiring users to explicitly declare every slot ticks a box for making come self-explanatory, but one of the things that make Perl a powerful language is the ability to add shortcuts to "Do what I mean".)

In the above use case, would could work around this by having a foo slot in the Bar object and the other slots lazily default to the appropriate values from it, but what if the Bar object just doesn't need it (especially if the foo takes up a lot of memory)?

Being able to rewrite or adjust constructor arguments is a useful feature, especially as code evolves and a developer wants to gracefully handle older arguments.

robrwo commented 3 years ago

It's possible that discussion in #27 relates to this.

robrwo commented 3 years ago

I'll give a more concrete example. I maintain some Catalyst and Mojo web applications. At $work we have various helper classes for the business logic. It's often useful to say in the application

my $x = Foo->new( ctx => $c );

where $c is the Catalyst context. It's a monstrously huge object that Foo only needs to initialize attributes from, but otherwise can simply be thrown away once the object is built.

Ovid commented 3 years ago

After considerable discussion, for the MVP, there is no BUILDARGS or equivalent. We use an alternate constructor.

common method new_from_ctx (%arg_for) {
    my $c    = $arg_for{ctx} or croak("You must pass ctx to new_from_ctx");
    my %args = # extract args from $c
    return $class->new(%args);
}

We will revisit this after the MVP unless we there is a compelling reason it must exist for the MVP.

Ovid commented 2 years ago

Closing this to ensure tickets are just for the MVP. We will revisit later.