Arguments and attributes with the same name

Jonathan M Davis jmdavisProg at gmail.com
Thu Mar 4 12:45:18 PST 2010


Clemens wrote:

> bearophile Wrote:
> 
>> Ary Borenszweig:
>> > So you suggest to forbid having an argument name that
>> > matches an attribute name? Or require this. for attribute access?
>> 
>> I prefer the compiler to give an error when an argument has the same name
>> of an attribute, it's tidier.
> 
> I'd rather not have that, I like to write my constructors in the way you
> have shown in your first post:
> 
> class Foo {
>     int x;
>     this(int x) { this.x = x; }
> }
> 
> Saves me from inventing silly names for the parameters (like "theX") or
> appending ugly pre-/suffixes like an underscore.

Agreed. It would be _highly_ annoying if you couldn't have parameters to 
member functions (constructors or otherwise) which had the same names as 
member variables. And if you have protected member variables with the same 
name as a parameter, it would get even worse. Not to mention, properties 
(which may not be associated with a member variable at all) would likely 
fall in the same category and it would be even worse.

x = x;

is clearly an error. No,

x = x + 1;

is not, but it's not at all ambiguous. If you want to make absolutely 
certain that you never have this issue, either always use this or use the 
more common solution of appending your member variable's names with _ or m_,
so you'd get

_x = x;

I really don't think that this is a big problem. And it would be really 
annoying if you were to restrict parameter names based on the names of 
member variables or properties.

- Jonathan M Davis



More information about the Digitalmars-d mailing list