Named constructors

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Jan 10 16:22:27 UTC 2019


On Thu, Jan 10, 2019 at 02:35:33PM +0000, JN via Digitalmars-d wrote:
> On Thursday, 10 January 2019 at 13:53:40 UTC, Atila Neves wrote:
> > 
> > What's the _real_ difference between `someFunc(firstName="Alice")`
> > and `someFunc(FirstName("Alice"))`? The former saves one character?
> > Is that really worth the cost of language support? I have a feeling
> > a lot of feature requests neglect that each and every one of them
> > has a cost, and there's only enough budget for so many.
> > 
> Isn't there a performance cost added when using structs like that?

I highly doubt it.  Esp. with D's structs, which are designed to be
"glorified ints", i.e., they are designed precisely to be passed as
though they were their constituent fields. And anyway, it's nothing an
optimizer can't eliminate the cost for (if there's any to begin with).


> And the real cost is the fact that you have to create all those
> structs meticulously and you can only use that with functions that
> expect such usage.

I started some time ago to sketch a generator template that uses
introspection to auto-declare such structs for a function and generate
overloads that accept named parameters in any order. Didn't have the
time to finish it, unfortunately. But the idea was to make it as
painless as possible to use this idiom.


> With language support, you could have named arguments for every code
> there exists.

Good point.


> Anyway, the fact that arguments are named are only a bonus, the real
> strength of named arguments comes with optional arguments. Look at the
> Builder pattern, it's pretty much a workaround for lack of
> named/keyword arguments.
[...]

These days, whenever my functions start needing so many optional
arguments that this becomes a problem, I just start using a struct to
encapsulate them instead. I wouldn't claim it's the perfect solution,
but it does pretty much have equivalent functionality: you can pass
values in order (MyArgs(...)), or pass them by name (MyArgs args;
args.field1 = 123;), and there can be default arguments (default field
values). It does need a bit more typing, but other than that it works
pretty well.

And it even supports things a language-backed named argument feature
can't handle: inheriting from another Args struct ("inheriting" another
function's arguments) and easy passing between a set of functions that
share the same set of parameters (just pass the struct instead of 10
arguments each time).


And just to be clear, I'm not *against* adding named arguments to D.
Just saying that you *can* get pretty far with what's currently there.


T

-- 
Change is inevitable, except from a vending machine.


More information about the Digitalmars-d mailing list