property syntax strawman

Oliver Hoog kingboscop at gmail.com
Sun Aug 2 04:52:57 PDT 2009


John C schrieb:
> Walter Bright wrote:
>> Having optional parentheses does lead to unresolvable ambiguities. How 
>> much of a problem that really is is debatable, but let's assume it 
>> should be resolved. To resolve it, a property must be distinguishable 
>> from a regular function.
>>
>> One way is to simply add a "property" attribute keyword:
>>
>>   property bool empty() { ... }
>>   property void empty(bool b) { ... }
>>
>> The problem is that:
>>
>> 1. there are a lot of keywords already
>> 2. keywords are global things
> 
> Well, property probably isn't too common a variable name, so it 
> shouldn't impact existing code.
> 
>>
>> The alternative is to have a unique syntax for properties. Ideally, 
>> the syntax should be intuitive and mimic its use. After much fiddling, 
>> and based on n.g. suggestions, Andrei and I penciled in:
>>
>>   bool empty { ... }
>>   void empty=(bool b) { ... }
>>
>> The only problem is when a declaration but not definition is desired:
>>
>>   bool empty;
>>
>> but oops! That defines a field. So we came up with essentially a hack:
>>
>>   bool empty{}
>>
>> i.e. the {} means the getter is declared, but defined elsewhere.
> 
> Would unimplemented setters look like this:
> 
> void empty = (bool b) {}
> 
> ?
> 
>>
>> What do you think?
> 
> Looks a bit odd. Perhaps it's just the unfamiliarity of the syntax. Most 
> of us got used to templates, eventually.
> 
> My own syntax suggestion requires no new keywords (contextual or 
> otherwise).
> 
> interface INameable {
> 
>   string name {
>     ();
>     (value);
>   }
> 
> }
> 
> class Person : INameable {
> 
>   private string name_;
> 
>   string name {
>     () { return name_; }
>     (value) { name_ = value; }
>   }
> 
> }
> 
> In the above example, "value" could be anything the class designer wants 
> - to the compiler, empty parentheses () represent the getter, (blah) the 
> setter.

Looks good. You could have wrapper properties like:
---
class Clock {
	private int sec_;
	int min {
		() {return sec_ / 60;}
		(m) {sec_ = m * 60;}
	}
}
---
auto c = new Clock;
c.min = 2;
++c.min; // gets translated to "c.min = c.min + 1;" and evaluates to 
c.min called after that call
c.min++; // gets translated to "c.min = c.min + 1;" and evaluates to 
c.min called before that call
// same with other ops unless they are explicitely otherwise defined
---

(And all non-property functions shouldn't be allowed to be called in 
assign-style or without parentheses.)



More information about the Digitalmars-d mailing list