http://www.perlmonks.org?node_id=912502


in reply to Re^3: How should named paramater keys be named?
in thread How should named paramater keys be named?

Once again it depends on the complexity of the parameters that are being supplied. One, two, three parameters exposed to the public maybe not an issue, and agreeably named parameters probably not needed.

However, if the interface in to the whatever you are calling requires a more complicated set up, then I would say that named parameters are in order. Now with that said, when using named parameters they better be consistent throughout the entire program. Moreover, I would go so far as to say they should also be lower case and clearly documented. Personally I see named parameters having value, but the value is only obtained where exposed to the public. Code that is on the back end that users cannot call directly why would they be needed--you already have established programmatic control over the parameters.

Yes, I use named parameters outside of a constructor -- my previous restrictions still apply ( internal NO, user called YES ). An example would be when I want to enable a local debug. Keep in mind that the routine already has other values being passed.

sub foo { my $o = { q{debug} => 0, ## debug 0|1. q{db} => SQL_DB, ## sql db. q{host} => SQL_SERVER, ## sql server. q{port} => SQL_PORT, ## sql server port. q{user} => SQL_USER, ## sql user. q{pass} => SQL_PASS, ## sql user pass. @_ }; ## do your safety checks... my $dsn = q{DBI:mysql:database=} . $o->{'db'} . q{;host=} . $o->{'host'} . q{;port=} . $o->{'port'}; my $objSQL = eval { DBI->connect( $dsn, $o->{'user'}, $o->{'pass'}, { 'PrintError' => 0, 'RaiseError' => 0 } ); }; if ( ( $@ ) || ( ! defined $objSQL ) ) { ## maybe we only want to show the error if in debug?? print STDERR $DBI::errstr if ( $o->{'debug'} ); return undef; } DBI->install_driver( q{mysql} ); return $objSQL; }

Now, I did not run check the code above, and it is ONLY an example of what can be done. Also, I do not expect everyone to agree with the code. So, not only does this allow a user to call the function, method, subroutine, etc... but it provides simple named parameters by which it can be called. More importantly, it allows the end user to call it without having to care about the order and if the parameter is not specified then it is defaulted. I understand that one cannot always default to a meaningful value, but this is just an example. As far as my style goes, I do not like the leading hyphen, nor do I like the mixed case, such as the DBI Connect implements. But that is just my style. Honestly, I prefer the shorter single case format.

Finally, named parameters have their place and can provide value. The trick is to balance how and when they are used. Is there a cost? Yes. Can they provide a more robust public interface? Yes. Can they be overused? You better believe it.