Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

(kudra: obj shift) Re: Shift versus Sanity

by kudra (Vicar)
on Apr 24, 2002 at 11:07 UTC ( #161568=note: print w/replies, xml ) Need Help??


in reply to Shift versus Sanity

Sometimes shift is just the nicest way to get the job done. For example:
my $self = shift; my %hash = @_;
I believe that makes more sense than the alternatives. $self doesn't really have anything to do with the rest of the arguments, so it is logical to take it off first and then deal with the other options.

I probably wouldn't use shift to get any of the other arguments, however. It's probably clear from the example that I prefer named arguments, and shift is not a good way to deal with them. Update: A rant about named arguments can now be found right here in the page instead of by viewing the page source.

Named arguments are good if you have a lot of arguments and don't want to look up the order every time you make a function call.

But the main reason I use them is that it is expandable. It looks a bit silly when you only have one or two arguments, but it has paid off for me often enough. Compare these two function calls:

mysub(name => 'foo', number => 'three'); mysub('foo', undef, undef, undef, 'three');
In one, it's very easy to see what arguments are being used. In the other, you'd be lucky to get your arguments in the right positions.

Of course, if you're still writing the code that uses this function, you can change all your function calls so it is possible to re-arrange the order of your arguments to put the optional ones at the end. But what if they're all optional? Or what if the code is already in production, but needs to be expanded for new uses without breaking the old uses? The most readable result will most likely be the one that uses named arguments.

All in all, I'd rather take the risk that the function never needs more arguments and I have to type a few extra words with every function call than that it does expand and I can't easily accomodate it.

Of course I don't consider it a hard rule. Plenty of my code doesn't use named arguments. But unless I have a good reason not to, I do use them.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://161568]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (2)
As of 2020-12-05 05:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How often do you use taint mode?





    Results (63 votes). Check out past polls.

    Notices?