On Friday, March 20, 2015 11:54:20 w0rp via Digitalmars-d wrote: > On Thursday, 19 March 2015 at 22:04:01 UTC, Walter Bright wrote: > > Accessor functions that merely return a field variable are bull > > anyway. > > > > Hear, hear! I start with first with... > > public string name; > > Then if I really want to change the way the value is assigned or > maybe add in some validation, possibly with contracts, I use > @property. > > (This is only for things which are supposed to be part of the > public API anyway.) > > I would still document the property, though. I feel I need to > justify why every member exists in a struct or class. That's > mainly a data layout concern, and that's just how I happen to > feel about it.
In principle, it would be great to be able to do what you're suggesting, but if you're dealing with a public API, it really doesn't work, because you can do things with a variable that you can't do with a @property function - like pass it by ref - and some are legal for both but have different meanings (e.g. taking its address). So, if you use a public variable as part of the API, and you want then want to make it so that it does validation later or so that the value is calculated or anything that would make it so that you want to use a @property function instead of a public variable, if you change it to be a @property function, you're probably going to break someone's code somewhere. So, it really doesn't work to change a public variable into an @property function later unless you're the only one using the code in question, or you don't mind breaking other people's code. Another thing to consider is that the type's invariant will be called on an @property function, whereas it won't be called when you access a public variable. Two possible solutions for this which have been suggested before but never implemented are: 1. Make it so that if you declare public @property string name; it generates a private variable for name (e.g. _name) and getter and setter property functions called name. So, you don't have to type everything out explicitly, but you still get the encapsulation. 2. Make it so that if you declare public @property string name; it's a public variable as it would normally be, but it's then illegal to do anything with it that you couldn't do with a property function (e.g. pass it by ref). But without a lanugage enhancement of some kind, using public variables in an API that's being used by anyone else either makes it so that you can't ever change it so that you're using a property function, even if you need to later, or you make it so that when you do change it to a property function, you risk breaking existing code (often, which you don't even know exists, because it was written by someone else). - Jonathan M Davis