The problem with @properties in D

Mehrdad wfunction at hotmail.com
Mon Dec 12 16:25:33 PST 2011


In every language I've seen that has "properties" (C#, Python), they are:

     - _Defined_ like methods
     - _Used_ like variables

The trouble is, this isn't true with D.

Consider:

struct Struct
{
     int delegate() randgen1 = ...;
     @property
     int delegate() randgen2() { ... }
}

Struct s;
auto result = s.randgen2();    // This doesn't do the user expects

It is *not* possible, in D, to transparently use either one -- you have 
to treat properties, like methods, not like variables. Except that this 
is inconsistent -- in most other cases, you don't need to do that.

Or for example:

Struct s;
auto a = &s.randgen1;
auto b = &s.randgen2;  // Should be an error

IMO, properties should not be callable with parentheses at all. 
Something like C# -- they should generate getter and setter methods 
instead, or the like.
Furthermore, taking the address of a property should only work if you 
can take the address of its _value_. If you need the address of the 
actual function, then I think a corresponding getter method might be 
easier to use.

It gets even /worse/ in templated code, because you have no idea whether 
an alias is referring to a property or to a variable or whatever.

Making this change would obviously break code, but the break is 
obviously _trivial_ to fix: just remove extra parentheses. It won't 
exactly be the kind of breakage that causes headaches.

So should this be fixed?


More information about the Digitalmars-d mailing list