Module level variable shadowing
H. S. Teoh via Digitalmars-d
digitalmars-d at puremagic.com
Fri Jun 27 22:11:39 PDT 2014
On Sat, Jun 28, 2014 at 06:37:08AM +0200, dennis luehring via Digitalmars-d wrote:
> Am 27.06.2014 20:09, schrieb Kapps:
[...]
> >struct Foo {
> > int a;
> > this(int a) {
> > this.a = a;
> > }
> >}
> >
>
> forgot that case - but i don't like how its currently handled, maybe
> no better way - its just not perfect :)
Actually, this particular use case is very bad. It's just inviting
typos, for example, if you mistyped "int a" as "int s", then you get:
struct Foo {
int a;
this(int s) {
this.a = a; // oops, now it means this.a = this.a
}
}
I used to like this shadowing trick, until one day I got bit by this
typo. From then on, I acquired a distaste for this kind of shadowing.
Not to mention, typos are only the beginning of troubles. If you copy a
few lines from the ctor into another method (e.g., to partially reset
the object state), then you end up with a similar unexpected rebinding
to this.a, etc..
Similar problems exist in nested functions:
auto myFunc(A...)(A args) {
int x;
int helperFunc(B...)(B args) {
int x = 1;
return x + args.length;
}
}
Accidentally mistype "B args" or "int x=1", and again you get a silent
bug. This kind of shadowing is just a minefield of silent bugs waiting
to happen.
No thanks!
T
--
Designer clothes: how to cover less by paying more.
More information about the Digitalmars-d
mailing list