Arguments and attributes with the same name

Ary Borenszweig ary at esperanto.org.ar
Thu Mar 4 05:27:19 PST 2010


bearophile wrote:
> This is correct D code, but I think it's a bad practice to write code like this, where method arguments have the same name as instance/static attributes of the class/struct.
> 
> class Foo {
>     int x;
>     this(int x) { this.x = x; }
>     void inc(int x) { this.x += x; }
> }
> struct Bar {
>     static int x;
>     void inc(int x) { Bar.x += x; }
> }
> void main() {}
> 
> 
> In Python this problem is less important because the language forces you to always prepend the argument names with "self.", while in D the "this." is optional.
> 
> In the last years D has added errors for situations where you use duplicated names, for example in nested scopes or in with statement.
> 
> So do you think it's a good idea to forbid/warn against such name clash?

This can be solved if the compiler warns when an assignment is from a 
variable to the same one.

x = x; // error: assignment has no effect



More information about the Digitalmars-d mailing list