DIP4: Properties

Nick Sabalausky a at a.a
Sat Jul 25 14:18:43 PDT 2009


"Daniel Keep" <daniel.keep.lists at gmail.com> wrote in message 
news:h4ejrk$12vv$1 at digitalmars.com...
>
> Andrei and Rainer have come up with an alternative that might work.
>
.....
>
> Basically, the idea is that this:
>
> interface I
> {
>    int foo();
>    int foo(int);
> }
>
> becomes:
>
> interface I
> {
>    int opGet_foo();
>    int opSet_foo(int);
> }
>
...etc...


My admittedly sarcastic thoughts on this whole group of property proposals 
(and pardon my grumpiness):

A 'for' loop is great, but one of the most common uses for it is to iterate 
over a collection. And for that, there are certain issues with using 'for' 
that other languages have solved by adding a special 'foreach'.

But, I see no reason to add a special 'foreach' syntax (and certainly not a 
new keyword!), because we have most of what we need for 'foreach' in place 
already:

class Foo
{
    int[] content;
    Iterator opIterator()
    {
        return new Iterator();
    }
    class Iterator
    {
        private index=0;
        int opGetNext()
        {
            return content[index++];
        }
        bool opHasNext()
        {
            return index < content.length;
        }
    }
}

void main()
{
    auto f = new Foo();
    // populate f

    int index;
    int val;
    auto iter = f.opIterator();
    for(int index=0, int val=iter.opGetNext();
        iter.opHasNext(); index++, val=iter.opGetNext())
    {
        // Use index and val
    }
}

Granted, that's ugly and won't satisfy the people who like DRY and brevity, 
but we can solve that with mixins:

class Foo
{
    int[] content;
    mixin(iterator!(int,
        q{
            private index=0;
        },
        q{
            return content[index++];
        },
        q{
            return index < content.length;
        },
    ));
}

void main()
{
    auto f = new Foo();
    // populate f

    mixin(foreach!(f, int, "val", "index",
        q{
            // Use index and val
        }
    ));
}

And then everybody loves this new idea because it's so D-like and makes 
minimal changes to the syntax/compiler.

And then we all spend every weekend wondering why the hell nobody wants to 
use our wonderful language.

Don't get me wrong, using these "foo.opGet" ideas for *behind-the-scenes 
implementation* of properties sounds like it may very well be the right way 
to go. But without a real dedicated syntax to cover it all up, it's just 
idiotic.





More information about the Digitalmars-d mailing list