mauke / Function-Parameters

Function::Parameters - define functions and methods with parameter lists ("subroutine signatures")
https://metacpan.org/pod/Function::Parameters
18 stars 19 forks source link

Add ""= #11

Open schwern opened 9 years ago

schwern commented 9 years ago

Similar to #10, it has the same rationale but I'm doing this in a separate issue since it requires making up new syntax.

The third common reason to apply a default is for an empty string. ||= can't be used because "0" would be valid. ""= would be equivalent to...

$arg = "default" if !defined($arg) or !length($arg);
mauke commented 9 years ago

What's your use case for this?

schwern commented 9 years ago

//=, ||= and ""= are all for the cases where the caller has passed in something but it's trash, something that happens more often than we'd like in Perl. As the writer of the subroutine, I don't have control over how it's called. undef will pass the required parameter check, but the value is useless. It's better to apply a useful default than proceed with undef. //= is for when a false value is ok. ||= is for when only true values are ok. ""= is for when only non-empty strings are ok.

One could argue that instead the bogus values should instead be rejected by a type constraint. While I like type constraints, I don't think they're ready to be applied universally, and Function::Parameters is a universally useful module. Types aren't well accepted in Perl, they're slow, and writing custom types (such as "non empty string") is a PITA. It's worthwhile to support good, defensive styles that don't use types.

Here's an example which ensures the test always has a name. It's a thing that will be displayed, so it should be non-empty. //= is insufficient as it allows an empty string. ||= is insufficient as it disallows 0.

func is($have, $want, $name ""= qq['$have' eq '$want'] ) {
    return ok($have eq $want, $name);
}

Maybe you're building a command out of the arguments and want to make sure every piece is filled in. Passing in a non-blank string might allow a security problem or for a piece to be misinterpreted.