Redundancies often reveal bugs

Daniel Gibson metalcaedes at gmail.com
Fri Oct 1 01:49:51 PDT 2010


On Fri, Oct 1, 2010 at 9:50 AM, Peter Alexander
<peter.alexander.au at gmail.com> wrote:
>> I dont know if it is, but IMO it really should be an error to declare local
>> variables that hide member variables.
>
> I disagree. I always do that in constructors:
>
> int x, y;
> this(int x, int y)
> {
>  this.x = x;
>  this.y = y;
> }
>
> I think you would annoy a lot of people if it was forbidden.
>

I do the same, but got a nasty bug that took me hours to find because
in one condition later down the constructor I forgot the "this."
prefix. this kind of bug is hard to spot by just reading the code.

IMHO it's quite tedious to do all these  assignments in a constructor
anyway - it'd be cool to have some possibility to say "this
constructor argument should be assigned to the classes field of the
same name", like

int x, y, z;

this(class int x, class int y, int a) {
  // this.x and this.y are set implicitly
  this.z = (x+y)/a;
}

or something like that. Dunno if "class" is an appropriate keyword for
that (probably not), but it should suffice to illustrate the idea.
Well, maybe "this(int this.x, int this.y, int a)" would be better.
And maybe this wouldn't need addition to the language at all but could
be done with some template/string-mixin magic.
I haven't really thought this through, but *some* possibility to do
this (assign constructor- or even function-arguments to class field of
same name) would be cool :-)


More information about the Digitalmars-d mailing list