Subject: | Making conditional code easier |
The classic middle-conditional problem which in straightline code is
A()
if(COND) { B() }
C()
is awkward to express with Future-returning functions. Current best attempt looks something like
A()
->then( sub {
if(!COND) { return Future->done() }
B();
})
->then( sub { C() });
One possible solution would be a 'then_if' method on Future instances, which takes a condition and a code block
A()
->then_if(COND => sub { B() })
->then( sub { C() }
Easy enough to implement
sub then_if
{
my $self = shift;
my ( $cond, $code ) = @_;
return $self->then($code) if $cond;
return $self;
}
Though this obviously only restricts it to conditions that don't depend on the result of A().
Another thought is a Future->if class method
A()
->then( sub { Future->if(COND, sub { B() }) })
->then( sub { C(); })
which in the case of a false condition can just yield an empty Future->done. But at that point it's not much of an improvement on
->then( sub { COND ? B() : Future->done } )
in such a small case as this, though it does win out in neatness if the B() code is in fact a much longer block of statements, rather than a simple function-call expression.
--
Paul Evans