DIP23 draft: Fixing properties redux
Jonathan M Davis
jmdavisProg at gmx.com
Tue Feb 5 17:24:30 PST 2013
On Wednesday, February 06, 2013 09:56:40 kenji hara wrote:
> I fully agree with Andrei.
> I can see that swapping public data field to property function call is not
> rare, but in almost case, such refactoring also intends to add
> encapsulation.
>
> struct S {
> // Before swapping
> int _data;
>
> // After swapping
> private int _data;
> @property int data() { return _data; }
> @property void data(int n) { enforce(n > 0); _data = n; }
> }
> S s;
> int n = s.data;
> s.data = 1;
> //int* pdata = &s.data;
> // changed to disallowed ... it is mostly intended.
You misunderstand. We don't _want_ taking the address to work. We _want_ the
encapsulation. We just don't want to have to write all of the boilerplate
code.
The idea is that you want to be able to just make it a variable first, because
you don't need to do any extra checks or anything else but get or set the
variable. So, having to declare the setters and getters is overkill. The
problem is that if you just declare it a variable, then people can take the
address of it or pass it by ref - which you don't want. You _want_ the
encapsulation up-front. You just don't want to have to bother with all of the
boilerplate code required to do it. That's why some of us have suggested
making it so that you can mark variables with @property. That then either
makes it illegal to do anything with it which you couldn't do with a property
function (e.g. take its address), or it simply lowers it to the getters and
setters, making it so that you _do_ have the property functions in the
beginning. You just don't have to write them explicitly. Then later, if
refactoring requires that you add additional checks or other operations to the
getter and/or setter, then you explicitly declare the property functions.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list