The problem with @properties in D

Robert Jacques sandford at jhu.edu
Tue Dec 13 08:15:08 PST 2011


On Tue, 13 Dec 2011 07:25:10 -0500, Somedude <lovelydear at mailmetrash.com> wrote:
> Le 13/12/2011 01:25, Mehrdad a écrit :
>> 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?
>
> My question is: what is the use case for properties in D ?

The original use case for properties (in general) was to allow source level compatibility when one re-factored a public field from a variable to a method. Since then, properties have become a common tool to hide fields from the public interface (to allow for overloading, etc) but retain field like syntax. In D, the technical use case for @property was to resolve an ambiguity when re-factoring a zero argument delegate field to a method. Also, there was a cognitive dissonance between D's properties and those of C# and python.


More information about the Digitalmars-d mailing list