DIP23 draft: Fixing properties redux

Jonathan M Davis jmdavisProg at gmx.com
Mon Feb 4 22:13:17 PST 2013


On Monday, February 04, 2013 23:18:57 Andrei Alexandrescu wrote:
> On 2/4/13 10:30 PM, Chad Joan wrote:
> > On 02/04/2013 05:28 PM, Andrei Alexandrescu wrote:
> >> On 2/4/13 2:04 PM, Jonathan M Davis wrote:
> >>> We could save a lot of boilerplate code if we can simply make it
> >>> variables and
> >>> property functions guaranteed to be swappable without breaking code.
> >> 
> >> I think this is quite powerful. The way we can do this is by making
> >> properties emulate a subset of actual variables.
> >> 
> >> Andrei
> > 
> > I agree with Jonathan.
> > 
> > Please do not make them a subset. Make them as identical as possible.
> > The subset thing makes them no longer "swappable". Allow variables to be
> > marked with @property to limit them to operations that @property
> > functions can do, and make sure @property functions are limited to what
> > @property variables can do (ex: no address-of!). With that in hand,
> > they'll be very swappable.
> 
> The purpose is to replace members with properties, not to change one's
> mind back and forth. There will be no marking of variables with
> @property as that can be easily achieved by actually making them properties.

One of the main purposes generally given for having properties is so that you 
can make them public variables when you don't need them to do anything but get 
and set the member variable, but you can still make it a function later when 
you need to add other stuff to it (such as checking the value that it's being 
set to). One of the primary reasons for making a property function act like a 
variable is precisely so that you can switch between variables and functions 
when refactoring without breaking code.

Also, being able to mark variables as @property would save us a lot of 
boilerplate. Instead, it's incredibly common to do stuff like

struct S
{
    @property int prop() @safe const pure nothrow
    { return _prop; }

    @property int prop(int value) @safe pure
    { return _prop =  value; }

    private int _prop;
}

That's a lot of extra code just to buy some encapsulation. If we could do

struct S
{
    @property int prop;
}

we could really reduce the amount of boilerplate code surrounding member 
variables. Even if putting @property on a variable simply lowered to the 
property functions rather than it still be a variable, it would be a big help. 
But without either that or marking variables with @property so that you can't 
do anything to them that you can't do to a property function, we lose the 
ability to make a property a variable when the getters and setters are 
unnecessary, and that means that we're stuck with a lot of extra boilerplate.

- Jonathan M Davis


More information about the Digitalmars-d mailing list