Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RFE: Type::Params: coerce undef to default value #142

Open
djerius opened this issue May 20, 2023 · 2 comments
Open

RFE: Type::Params: coerce undef to default value #142

djerius opened this issue May 20, 2023 · 2 comments

Comments

@djerius
Copy link
Contributor

djerius commented May 20, 2023

It would be useful to be able to define a parameter signature which would coerce undef to the default value for the parameter. As an example, with a signature of

signature_for table_generator => (
    named => [
        cell_span => Enum[ DISPLAY_CELL_SPANS ],
                     { default => DISPLAY_CELL_SPAN_MULTI },
);

I currently have to check that the cell_span parameter is defined before passing it, otherwise I'll get a type error, which leads to things like this:

my $generator = table_generator(
    ( defined $args{cell_cpan} ?
      ( cell_cpan => delete $args{cell_cpan} ) : () ),
);

If the bike-sheddable undef_is_default flag was set for the cell_span parameter, then this would turn into:

my $generator = table_generator(
      cell_cpan => delete $args{cell_cpan}
);

PerlX::Maybe is an option, but I believe that the ability to conditionally coerce undef to the default in the signature results in clearer code.

@tobyink
Copy link
Owner

tobyink commented May 22, 2023

I'd suggest doing something like:

signature_for table_generator => (
    named => [
        cell_span => Maybe [ Enum[ DISPLAY_CELL_SPANS ] ]
    ...
);

my $cell_span = $args->cell_span // DISPLAY_CELL_SPAN_MULTI;

@djerius
Copy link
Contributor Author

djerius commented May 22, 2023

That does move the logic out of the caller, but it moves the setting of defaults for this parameter out of the signature and into the body of the subroutine.

If multiple parameters have defaults, specifying them in a single place makes for more understandable and maintainable code; I find that the signature is the natural place for them, as the boilerplate code required to initialize them outside of the signature detracts from the purpose of the subroutine. Having them in the signature provides both aesthetic and functional benefits.

There will always be oddball parameters requiring some sort of custom initialization which won't fit into the signature, but I think that passing undef is sufficiently common that it warrants specialized support in the signature.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants