Just a thought: read-only fields

Oliver Hoog kingboscop at gmail.com
Tue Aug 4 07:17:59 PDT 2009


Sergey Gromov schrieb:
> Mon, 3 Aug 2009 22:04:51 -0400, Nick Sabalausky wrote:
> 
>> It's been established in the recent epic-discussions on properties that one 
>> of the biggest uses for properties is to implement publically read-only (but 
>> privately-writable) fields. That got me thinking, why not actually have real 
>> publically read-only fields instead of merely emulating them with 
>> properties? They are, after all, a fairly common idiom.
>>
>> // *Not* an actual syntax proposal, but just to get the idea across:
>>
>> private @publicread int foo;
>>
>> // The class sees it as "int", but everything else sees it as "const(int)"
>> // ...or something like that...
> 
> Um... @publiconst? XD
> 
> or
> 
> private int foo;
> public alias const foo foo;
> 
> or even
> 
> private public(const) int foo;
> 
> Weird...  OTOH this should be trivial from the implementation POV.  On
> the even other hand this only worth considering if actual properties are
> dropped because properties are more generic and you *can* implement a
> read-only field with them.  Maybe some syntactic sugar is in order if it
> really is such a common thing.

Sounds good. Although I would like to keep the possibility that 
functions can be used as properties because there are cases when it's 
desirable. E.g:
---
class Clock {
	private int sec_;
	void sec(int s) {sec_ = s;}
	int sec() {return sec_;}
	void min(int m) {sec_ = m * 60;}
	int min() {return sec_ / 60;}
}
---
Here, only the "sec" property has a variable but "min" can be called the 
same way. Suppose you want to store the time in minutes later. When you 
are allowed to have wrapper properties like this it's easier to change 
because it looks the same from the outside. And it's more consistent, so 
  coders don't have to think about what property was a function and what 
was a variable.
Often though, they are just trivial functions like "sec" here. For that 
case, it is reasonable to have a shorter form.



More information about the Digitalmars-d mailing list