Super easy struct construction question that I'm embarrassed to ask.

H. S. Teoh hsteoh at qfbox.info
Mon Jan 13 04:55:52 UTC 2025


On Mon, Jan 13, 2025 at 04:05:25AM +0000, Jim Balter via Digitalmars-d-learn wrote:
> On Thursday, 9 January 2025 at 22:08:31 UTC, Dennis wrote:
> > On Thursday, 9 January 2025 at 22:01:59 UTC, WhatMeWorry wrote:
> > >     this(Location locaction, uint f) {
> > >         this.location = location;
> > >         this.f = f;
> > >     }
> > 
> > 
> > You misspelled the parameter name 'locaction', so your assignment in
> > the constructor is a no-op:
> > 
> > ```
> > this.location = this.location
> > ```
> 
> Which is why languages like Zig disallow such code ... unused
> variables must be identified as such.

I wish there was some kind of syntactic sugar for assigning ctor
parameters to class members. This kind of boilerplate happens quite a
lot on OO-style code, and is a common place for typos and other such
careless mistakes, because it's just so repetitious that you don't
really pay attention to it when writing it.

Especially bad is naming ctor parameters with exactly the same
identifier as the class member, then it becomes non-obvious whether
occurrences of that identifier refers to the parameter or to the class
member.  A common convention is to append or prepend `_` to one of them,
but even that is easily overlooked, and a single-chararacter typo
reverts back to the same problem.  And it still doesn't address the main
issue, which is the blatant violation of DRY.

I've seen some D users use mixins to automate away the boilerplate, but
TBH it looks kinda messy, and isn't really conducive to the cases where
most ctor arguments are to be copied but one or two must be specially
treated.  Some kind of default ctor mechanism that still allows for
custom code where needed, would be really nice.


T

-- 
Without outlines, life would be pointless.


More information about the Digitalmars-d-learn mailing list