|Think about Loose Coupling|
Re: Re: Re: Context aware functions - best practices?by ihb (Deacon)
|on Jan 15, 2003 at 20:05 UTC||Need Help??|
An argument against this is that the user expects a list to be returned, not an array.
While I understand your argument I believe that it is the user that errors. The error lies in his expectation. If a subroutine is documented to return a list it's also implicitly documented only for list context. When calling such a subroutine in scalar context you can't expect anything to happen--even less something sane to happen; there are no lists in scalar context. Take sort() for instance. That's obviously a list-context function, and you don't expect it to do anything useful at all in scalar context. Aristotle's problem is not as clear, but my point is still that if a subroutine is documented to return a list it's only documented for list context. Every other behaviour is undefined.
But you also hit the nail when saying that we should code so that our routines get intuitive. So yes, I do partly agree with your argument.
In terms of intuition, most people intuitively expect the following two expressions to be equivalent:
my($x) = foo(...);
my $x = foo(...);
Yes, but this intuition is quickly counter-prooved by the numerous bugs that will come to any programmer expecting this. This is probably the first context bug that Perl programmers will meet. And usually, when past the newbie state, they don't get that wrong anymore. I too want to write easy-to-use code, but I expect a certain level of Perl understanding of my users, and list vs. scalar assignment is a basic thing in Perl.