Properties
Bill Baxter
wbaxter at gmail.com
Thu Jan 8 17:42:03 PST 2009
On Fri, Jan 9, 2009 at 9:59 AM, Miles <_______ at _______.____> wrote:
> Nick Sabalausky wrote:
>> A property setter is ALWAYS going to return nothing and
>
> Both the getter and the setter should return an rvalue. Properties exist
> so that they are interchangeable with real member variables.
Partly, but also properties exist to provide encapsulation of private state.
So you gotta be careful when you say they should always return an lvalue.
Returning a straight 'ref T' is pretty much the same as making the
member variable public,
in terms of the encapsulation it gives you.
class Foo {
private int _data;
ref int data() { return _data; }
void data(int d) {
data = d;
do_something_very_important();
}
}
auto foo = new Foo;
int*allyourdataisbelongtome = &Foo.data;
Bye bye encapsulation. Now I can change your data all I want without
you noticing.
Also it means if I later realize I actually wanted data to be a float
internally, I still have to keep an int member around to satisfy any
client code that depends on getting an integer lvalue back.
What I would like to see happen is that if a property setter doesn't
return an lvalue, then the compiler will jigger things around to do
everything in terms of calls to the setter. If it does return an
lvalue then it will use it directly.
> Something
> that is possible with member variables MUST also be possible with
> properties, in a transparent way for any code outside the class.
>
> For example:
>
> button.width = button.height = 50; // makes a square button
I agree that that should expand to something sensible, but that
example doesn't actually require the setters to return an lvalue. A
regular rvalue is fine for that.
You'd only need to return an lvalue for something like:
(button.height=50) += 3;
Or for something like change_integer( button.height = 50 ); where
change_integer takes a ref int.
Using the lvalue returned from a property assignment is really not
that common I think. Maybe I'm missing some big use case though.
On the other hand, things like ++x do get used as lvalues more
commonly I think. I'm fond of doing ++x%=N as a way to do a
wrapped increment. :-) In C++, anyway. In D it gives me "x += 1 is
not an lvalue".
--bb
More information about the Digitalmars-d
mailing list