Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enter by-name argument to a function in D?

Tags:

d

I am struggling on passing arguments by name to a function that has default parameter values defined:

import std.stdio;

void main() {

    void foo(int x=1, int y=2, int z=3) {
        writefln("x=%s, y=%s, z=%s", x, y, z);
    }

    foo(10, 20, 30); // ok, prints: x=10, y=20, z=30

    foo(z=30); // Error: undefined identifier 'z'
}

This is quite a basic need. Such a function can have 10 parameters or more and might be called multiple times with different set of arguments. It would be unbearable to list all the args everytime - it would require precise knowledge of positions that can even change in a new versions of my app. Or new version of my app can change default value a I would have to go through all my source code to change it.

I think so basic thing must be in such a comprehensive language like D.

like image 766
tlama Avatar asked Nov 07 '15 12:11

tlama


1 Answers

D does not have that feature. There were discussions about it but I doubt it will ever have named parameters...

It is debatable whether what you ask for is a "basic thing" or not. I am in the group of developers who think named parameters are just leading to complex code. Python is perfect example of that. I have seen functions taking 20 named parameters because over the years developers just kept adding them to the function which became a total mess...

When you have a function with 10 parameters, then your design is most likely to be wrong.

Finally, named parameters introduce extra overhead and affect performance. Here is an interesting article from the C# world: http://www.dotnetperls.com/named-parameters .

like image 152
DejanLekic Avatar answered Jan 01 '23 02:01

DejanLekic