Properties

Chad J gamerchad at __spam.is.bad__gmail.com
Sat Jan 10 23:24:07 PST 2009


dsimcha wrote:
> I'm starting to think that this properties thing is becoming a hopelessly
> complicated solution to a very simple problem.  The issue that brought this to a
> head in the first place was foo = foo + 1 vs. foo += 1.  Given that solving this
> case properly seems like a rather difficult problem, the solution of just defining
> foo += 1 to mean foo = foo + 1 (which is what was originally proposed before
> issues about properties of user-defined types were brought up) is starting to look
> appealing.  Yes, this might be inefficient on user defined types w/ operator
> overloading, but so is the equivalent in other languages:
> 
> SomeObject temp = myClass.getFoo();
> myClass.setFoo(temp + 1);
> 
> I figure the vast majority of cases are going to be primitive types anyhow (mostly
> ints), and if someone defines operator overloads such that foo += 1 produces
> totally different observable behavior than foo = foo + 1, that's just too
> ridiculously bad a design to even take seriously.  What do you think?  Is it worth
> ignoring a few hard cases in exchange for solving most cases simply and elegantly
> and without adding any new constructs?

foo = foo + 1 vs foo += 1 is not the only issue here.  Indeed, it is
rather one of the less important ones, since it tends to give you a
compile error instead of sending you on hours of debugging.

Bill already mentioned that properties returning callable things were a
problem.

There's another one too:

import tango.io.Stdout;

struct Foo
{
   char[] a = "Waait, something's wrong here.";
}

class Bar
{
    Foo m_foo;
    Foo foo() { return m_foo; }

    // Interestingly, write properties are completely optional
    //   when writing this kind of bug.
    // Foo foo( Foo value ) { return m_foo = value; }
}

void main()
{
    auto b = new Bar();
    b.foo.a = "Everything is fine.";
    Stdout( b.foo.a ).newline; //Prints "Waait, something's wrong here"
    // or writefln( b.foo.a ); if you prefer.
}

try it out (D1 code).

This demonstrates how easy it is to write broken properties.
It is related to foo = foo + 1 vs foo += 1 in that returning lvalues
might solve both of these.  However, as was mentioned before properties
are not lvalues, so making properties always return lvalues may very
well make more trouble for us.



More information about the Digitalmars-d mailing list