develooper Front page | perl.perl5.porters | Postings from November 2021

Is signature arity checking too strict?

Thread Next
From:
Paul "LeoNerd" Evans
Date:
November 25, 2021 15:03
Subject:
Is signature arity checking too strict?
Message ID:
20211125150337.438fa966@shy.leonerd.org.uk
In general, I like signatures. They're great. But there's one situation
in which I think the arity checking gets it wrong. Passing too many
values for the signature should not be fatal.


In event-based code it's often the case that users pass in callbacks as
CODE references, expecting your event system to invoke them. If users
always pass me a callback and I always used to do 

   $cb->($thing)

and now I want to pass more data, before signatured subs it was always
safe to just do

   $cb->($thing, @more)

because in practice everyone just handled their args by doing:

   callback => sub { my ($thing) = @_; ... }

and nobody would mind the extra values.

But suddenly now if they used signatures for this by passing

   callback => sub ($thing) { ... }

then it'll complain at runtime if I pass any more values. Which sucks.

So right now we're basically forcing everyone to pass callbacks around
with a trailing slurpy, as `(..., @)`, at the end of their signature,
"just in case"

If we had some sort of introspection we could do some kind of
`bounded_invoke( $callback, @args )`  which would slice @args to no more
than the signature says it wants.

Though overall, I think signature checking has slightly the wrong
behaviour here. It should be asymmetric: die if too few values, but
only warn if too many.

It should warn from the caller's perspective on a name that can be
easily no warnings'd away

    {
      no warnings 'too_many_args';
      $callback->($thing, @more);  # silently discard if too many
    }

It's still experimental - it's not too late to change this ;)

-- 
Paul "LeoNerd" Evans

leonerd@leonerd.org.uk      |  https://metacpan.org/author/PEVANS
http://www.leonerd.org.uk/  |  https://www.tindie.com/stores/leonerd/

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About