The interaction of encapsulation and properties in D

Jonathan M Davis jmdavisProg at gmx.com
Thu Jul 11 00:49:55 PDT 2013


On Thursday, July 11, 2013 09:37:56 Jacob Carlborg wrote:
> I use public fields sometimes but as you say, there are problems. One
> can also run into problems with returning structs by value. The compiler
> would also need to do property rewriting to work flawlessly.

Property rewrites would definitely help (and I agree that we should have them), 
but they're far from enough to make variables and property functions 
interchangeable. I think that the only way that that could be done is if 
public variables could have additional restrictions put on them somehow (e.g. 
make it illegal to take their address or pass them by ref). Otherwise, there 
will always be a few things that will work with a public variable but not a 
property function.

A programmer can certainly choose to use public variables and just put up with 
broken code when swapping them with property functions later if you're in 
control of all your code (especially if you rarely use public variables in 
contexts where a property function would be illegal), but if you're releasing 
a public API which could be used by anyone, then I would argue that it's far 
better to just not use public variables, because the risk of code breakage is 
too high to be worth it.

Also, if we could make it so that something like

@property int value;

got lowered to property functions for you, then we could eliminate the 
boilerplate that frequently leads people to want to make member variables 
public rather than declaring property functions.

- Jonathan M Davis


More information about the Digitalmars-d mailing list