Make dur a property?

Jacob Carlborg doob at me.com
Thu Jan 24 00:41:33 PST 2013


On 2013-01-23 22:59, monarch_dodra wrote:

> In this context, what does it mean then to have something be "a property" ?
>
> I think we should remember what "@property" (as I understood it) is
> meant for: a function that can emulate being a object. The de-facto
> example being "front".

It's for a method emulating being a field/public instance variable.

> The "final" objective (as I understood it), is that you can publish your
> interface, and later, swap object/members for functions (and vice versa).

You cannot do this in D. There are at least two issues:

1. You cannot replace a non-final property, i.e. a method, with a field. 
Someone might have overridden the method in a subclass. In other 
languages like Scala a public instance variable is implemented as a 
method. In these cases you can switch freely between a property and an 
instance variable.

2. There are some issues with fields of a struct type being changed to a 
property, since they are usually passed by value. Example:

struct Bar
{
     int a;
}

class Foo
{
     Bar bar;
}

void main ()
{
     auto foo = new Foo;
     foo.bar.a = 1;
     assert(foo.bar.a == 1);
}

Changing Foo.bar to be a porperty like this:

class Foo
{
     Bar bar_;

     @property Bar bar ()
     {
         return bar_;
     }

     @property Bar bar (Bar bar)
     {
         return bar_ = bar;
     }
}

Now the assertion in main won't pass since the property is returning a 
value type that is copied. If you instead return by reference it will 
work, but then you can also set "bar" directly, bypassing the setter.

For this to work properly we would need property rewrite:

foo.bar.a = 1;

Should be turned into:

auto _tmp = foo.bar();
_tmp.a = 1;
foo.bar(_tmp);

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list