Struct Initialization syntax
Jim Balter
Jim at Balter.name
Thu Jul 26 02:29:43 UTC 2018
On Tuesday, 24 July 2018 at 16:35:32 UTC, H. S. Teoh wrote:
> On Tue, Jul 24, 2018 at 01:13:16PM +0000, Dukc via
> Digitalmars-d wrote:
>> On Tuesday, 24 July 2018 at 12:37:21 UTC, Cym13 wrote:
>> > That argument sounds quite dangerous to me, especially since
>> > my experience is on the contrary that constructor arguments
>> > are often named the same as the attribute they refer to. And
>> > what of mixed cases? I really wouldn't rely on anything like
>> > naming conventions for something like that.
>>
>> I was going to ask that how can they be named the same since
>> the argument would then shadow the member, but then I realized
>> that this works:
>>
>> struct S
>> { int a;
>> int b;
>>
>> this(int a, int b)
>> { this.a = a;
>> this.b = b;
>> }
>> }
>>
>> Yes, you are right.
>
> It works, but TBH it's quite a bad idea, and very confusing to
> read.
This is a very common programming style and is found in numerous
programming books and tutorials. Personal judgments as to whether
it's a good idea or confusing are completely beside the point;
designers of struct initialization syntax should not impose such
judgments on the rest of the world, possibly forcing people to
change their code and their texts.
> And TBH, if all the ctor is doing is copying its arguments to
> member variables, then we really should be more DRY and have
> special syntax for doing that, ala C++ (though the C++ syntax
> itself is pretty pathological... D could use better syntax, but
> the idea remains: get rid of redundancy like `this.a = a` or `a
> = _a`).
>
>
> T
This too is completely off topic. And there are hundreds of
thousands of extant lines of such code in various languages other
than C++ (or Scala, which has a different and more concise way to
avoid this boilerplate), and it hasn't been a big deal. Some
people use IDE forms/macros to fill in these common lines.
Back to the topic: I think #1 is noisy and confusing -- it looks
like a function or ctor call but isn't, and it looks like {...}
is a literal but isn't. I think #2 has to be considered in
conjunction with and dependent on named parameters. If named
parameters use the same syntax then #2 could be treated as if it
were a call to an implicit ctor that takes optional named
parameters corresponding to each member, which would provide
uniformity, but I think it's a bit dangerous and confusing, using
the same syntax to do two different things, initialization and
construction. I think #3 is straightforward, clear, and
consistent with existing struct initialization ... does it have
any downsides?
More information about the Digitalmars-d
mailing list