develooper Front page | perl.perl5.porters | Postings from January 2022

Re: Things you can't do in a signatured sub

Thread Previous | Thread Next
From:
Darren Duncan
Date:
January 20, 2022 05:20
Subject:
Re: Things you can't do in a signatured sub
Message ID:
6e506251-1e74-b6ee-f89f-ebe3cfe99781@darrenduncan.net
On 2022-01-19 12:43 p.m., Alexander Hartmaier wrote:
> I have one sad example to add: defining a sub that is passed as a callback to a 
> module which doesn't document the (number of) arguments and call it in different 
> parts with a different number of arguments. Example I'm just dealing with is 
> Mojo::RabbitMQ::Client.
> In the end I gave up and didn't specify a signature to avoid exceptions caused 
> by the different number of arguments.

So here's a question.  The way signatures work now, if one puts "@" at the end 
of the signature, does that say silently accept but throw away the extra 
arguments, or is there some way in a signature to say explicitly that you take a 
variable number of arguments and there is an array you can get "the rest" in? 
And if this feature is used in one way, eg with a signature of just "(@)" it 
kind of simulates the old way in that all the args are in an array.

> One more I can think of is different sub behavior depending on the number of 
> arguments, like multi-dispatch but inside the sub.
> Then naming the arguments might be hard because for example the first one holds 
> something different when paired with a second arg.

Aside from saying this seems like a poor design for a sub in the first place, I 
would say that as long as the number of arguments is the same, you can just give 
them names that indicate the options, for example "($foo, $bar_or_baz)" where 
"$bar" and "$baz" are the names you would have used if they were discrete 
arguments whose existence was conditional on the value of "$foo".

Similarly, I find its good to explicitly name variables or parameters to reflect 
that they might be optional or might have different things at different times. 
A common example is call something "$maybe_foo" rather than "$foo" if the thing 
doesn't actually have a "$foo" at all times and might instead be empty.  That 
makes the code more self-documenting and easy to understand

-- Darren Duncan

Thread Previous | 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