Suggestion: properties should be treated as 'virtual members variables'

Jarrett Billingsley kb3ctd2 at yahoo.com
Tue Sep 5 06:52:44 PDT 2006


"Kristian" <kjkilpi at gmail.com> wrote in message 
news:op.tfelx1zc5xlco7 at mist...

> I think properties should work just like they were data members: 
> everywhere you could give a data member you can also give a property.

I totally agree.  In my scripting language (or rather, in a previous 
incarnation of it), I wanted C#-style explicit properties, such as:

class Foo
{
    def int mX;
    property int x
    {
        set(int value)
        {
            return mX = value;
        }

        get
        {
            return mX;
        }
    }
}

..

def Foo f = new Foo();
f.x = 4;
writefln(f.x);
f.x += 6; // == f.x.set(f.x.get() + 6)
writefln(f.x);

Then I got even more general, and came up with namespaces + operator 
overloading:

class Foo
{
    def int function(int)[] mCallbacks;

    namespace callbacks
    {
        def int function(int)[] opGet()
        {
            return mCallbacks.dup;
        }

        def void opCatEq(int function(int) func)
        {
            mCallbacks ~= func;
        }

        def int function(int) opIndex(int index)
        {
            return mCallbacks[index];
        }

        def int length()
        {
            return mCallbacks.length;
        }
    }
}

...

def Foo f = new Foo();
f.callbacks ~= someFunc;
f.callbacks ~= anotherFunc;

for(def int i = 0; i < f.callbacks.length(); ++i)
    writefln("callback ", i, ": ", f.callbacks[i]);

def int function(int)[] cb = f.callbacks;

The advantage to this is that you can make really complex and abstract "data 
structures" out of what really amounts to syntactic sugar.  And unlike 
nested structs or classes, these members can be overridden, since the 
namespace only adds a piece to the name instead of creating an entirely new 
data structure.  And namespaces can live anywhere, and not just in 
classes...

OK, I'm going off on a bit of a tangent here, and it's doubtful Walter would 
go this far.  We can dream, though :)

But I think the point everyone is trying to make with wanting explicit 
property syntax is that if the compiler _knows_ about properties, it can do 
cool things with them.  I mean, Walter echoes this sentiment here: 
http://www.digitalmars.com/d/builtin.html .  Right now, the compiler doesn't 
know anything about properties; they're nothing more than a hackish way to 
write a function call. 





More information about the Digitalmars-d mailing list