Just a thought: read-only fields
Sjoerd van Leent
svanleent at gmail.com
Tue Aug 4 05:14:11 PDT 2009
Sergey Gromov Wrote:
> 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.
I like the idea. Writing a property requires more code, which is not essential. I think there can be many constructs. I don't know if private public(const) is easily parsed by the compiler though. perhaps this construct is:
pragma(read: const) private int foo;
otherwise a new keyword is necessary I think.
access(public, private) int foo;
Where the first parameter is the read situation, and the second parameter is the write situation. Or perhaps more verbose:
access(read: public, write: private) int foo;
Or maybe even better:
access(immutable: public, const: protected, mutable: private) int foo;
Meaning: everyone is able to read foo, subclasses can write to internal structures, but not change the object and only the object itself has full write access.
Just my 2 ct
More information about the Digitalmars-d
mailing list