Properties

Denis Koroskin 2korden at gmail.com
Sat Jan 10 22:35:08 PST 2009


On Thu, 08 Jan 2009 03:45:08 +0300, Vishaal <vishaal at nospam.com> wrote:

> Properties, such as array.length, should return lvalues to allow:
> a.length += 8;
> or other similar statements.

I'd like to point out another related issue that everyone seems to miss.

The following code is taken from a GUI library:

struct Rect
{
    int x, y, width, height;
    void reset() { x = y = width = height = 0; }
}

class Control
{
    //...

    Rect rect()
    {
        return _rect;
    }

    void rect(Rect newRect)
    {
        _resizeControl(newRect);
    }

    void _resizeControl(Rect rect)
    {
        // ...
    }

    private Rect _rect; 

    //...
}

Imagine rect is not a property but a field, first. How would you mutate it? I'd do it as follows:

Control c = new Control();
c.rect.reset();
c.rect.width = 100;

Both lines do nothing when field replaced with a property. Code is broken but there is no complains from compiler.
You should write the following code instead:

Control c = new Control();
auto tmp = c.rect;
tmp.reset();
c.rect = tmp;

auto tmp = c.rect;
tmp.width = 100;
c.rect = tmp;

but it doesn't look good. Compiler could be smarter in this regard - it could generate the code above automatically whenever a mutating method is called on a property.

And here is also another issue I can't wait to be fixed. The following syntax:
auto prop = foo.prop();

works for properties but not for fields, meaning that whenever code author decides to change it from property to field, user code is broken. Properties should not have optional braces!

As a result, properties and fields can not be used interchangeably until issues above are fixed.



More information about the Digitalmars-d mailing list