Module level variable shadowing

dennis luehring via Digitalmars-d digitalmars-d at puremagic.com
Fri Jun 27 23:19:14 PDT 2014


Am 28.06.2014 07:11, schrieb H. S. Teoh via Digitalmars-d:
> 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
>

thx for the examples - never though of these problems

i personaly would just forbid any shadowing and single-self-assign
and then having unique names (i use m_ for members and p_ for parameters 
etc.) or give a compile error asking for this.x or .x (maybe problematic 
with inner structs/functions)

but that could be a problem for C/C++ code porting - but is that such a 
big problem?




More information about the Digitalmars-d mailing list