The problem with @properties in D

Nick Sabalausky a at a.a
Mon Dec 12 16:52:52 PST 2011


"Mehrdad" <wfunction at hotmail.com> wrote in message 
news:jc661t$2mo5$1 at digitalmars.com...
> 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?

At the moment, you have to give DMD the "-property" switch to make it 
actually enforce the correct syntax/semantics for properties. When the 
feature was first put in a few releases ago, it was done like this to avoid 
breaking lots of code and to give people a chance to transition to it before 
finally forcing it (properties used to be done differently, and the problems 
with delegates, like you noticed, were a major reason for this @property 
stuff in the first place). Not sure when they were planning on finally 
flipping the switch and turning it on permanently, or at least on by 
default.

Has it maybe been long enough now?





More information about the Digitalmars-d mailing list