Passing function parameters by name
Don Clugston
dac at nospam.com.au
Wed Dec 5 08:32:39 PST 2007
renoX wrote:
> Don Clugston Wrote:
>> Artyom Shalkhakov wrote:
>>> Hello everyone.
>>>
>>> I suggest adding a new syntax for function parameter passing. To illustrate:
>>>
>>> void foo( int a, float b ) {
>>> // some code
>>> }
>>>
>>> void main() {
>>> foo( 1, 2.5f ); // classic
>>> foo( b : 2.5f, a : -3 ); // sort of struct initializer
>>> }
>>>
>>> Since named arguments can be passed in any order, they can be especially useful when a function has more than one parameter with a default value.
>>>
>>> This concept could be applied to template instantiation as well.
>>>
>>> -Artyom Shalkhakov
>> (Genuine question, not a flame):
>> To play devil's advocate for a moment: doesn't a long parameter list or lots of
>> default arguments indicate a poor design?
>
>
> A long list of parameter is not needed in order to have parameter passing par name useful: some compilers have added specific checks for memset (only 3 arguments) because quite a few people made an error in the order of parameters..
>
>
>> Essentially, the name of the argument becomes part of the API. Why isn't
>> function and object name good enough?
>
>
> I could ask the opposite question: why should we restrict the API to the function and object name instead of using the full data that we have?
Because it's simpler, and there's an enormous body of code (C, C++ for example)
which demonstrates a language can get by perfectly well without it;
Is the extra cost worth the benefit?
> To answer your question: passing parameter by name increase the readability of the source, reduce the number of mistake when writing the code (and with a good IDE the number of character to type would be the same).
But it also means that if you change the name of a parameter in a library, user
code will break. Certainly, you'd need some special syntax to specify which
parameters are part of the API, otherwise you get horribly brittle code.
Overload lookup rules could become complicated.
>> Named arguments are potentially a disastrous feature, if completely
>> unrestricted. It was when COM needed to support VB's named arguments that
>> Windows programming really nose-dived.
>
> Could you explain this point? (I know nothing about COM).
<flame>
VB allows you to call a C++ COM object by giving a list of argument names (as a
text array, with whatever stupid VB formats are possible) together with the
argument values as VB Variants. Languages like C++ were supposed to support any
combination the VB programmer chose to use. A massive complication of COM
code, just to support sloppy practice by VB programmers, and even then it was
only necessary because the VB interpreter was too lazy to put the parameters in
the right order.
</flame>
More information about the Digitalmars-d
mailing list