Named parameters in method calls

F

fishfry

Is the named parameter style of calling methods the officially right way
to do it these days? Or is there some debate? I'm talking about

my $foo = new Foo(FISH => 'tuna', DRESSING => 'mayo');

as opposed to Foo('tuna', 'mayo');

In other words if you do it the old (positional) way, is that considered
either hopelessly old-fashioned and/or bad coding practice?
 
T

Tassilo v. Parseval

Also sprach fishfry:
Is the named parameter style of calling methods the officially right way
to do it these days? Or is there some debate? I'm talking about

my $foo = new Foo(FISH => 'tuna', DRESSING => 'mayo');

as opposed to Foo('tuna', 'mayo');

In other words if you do it the old (positional) way, is that considered
either hopelessly old-fashioned and/or bad coding practice?

No, neither of that. Named parameters come in handy to smoothen the
interface a little when you have many arguments. Often I use them for
additional configuration options only:

my $obj = Class->new( $required_arg, -opt1 => 1, -opt2 => 2 );

The implementation of Class::new() would do something like that:

sub Class::new {
my $self = shift;
my $arg = shift;

croak "Required argument missing" if not $arg;

my %opts = @_;
...
}

This allows the user to just write

Class->new( $arg );

instead of the longer

Class->new( arg => $arg );

when he doesn't want to set any additional options.

Tassilo
 
C

ctcgag

fishfry said:
Is the named parameter style of calling methods the officially right way
to do it these days? Or is there some debate? I'm talking about

my $foo = new Foo(FISH => 'tuna', DRESSING => 'mayo');

as opposed to Foo('tuna', 'mayo');

In other words if you do it the old (positional) way, is that considered
either hopelessly old-fashioned and/or bad coding practice?

As far as I can tell, the named parameter method is common only when there
are lots of optional parameters. If all or most parameters are mandatory,
positional seems to be the common method.
 
G

gnari

As far as I can tell, the named parameter method is common only when there
are lots of optional parameters. If all or most parameters are mandatory,
positional seems to be the common method.

it is also useful if you foresee that the methods might be extended later.
this avoids breaking code that does not know about new parameters.
that is why this is popular in all sorts of modules.

gnari
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top