Ideas regarding flow control and loops

Marco Aurélio thecoreh at gmail.com
Sat Nov 3 06:26:48 PDT 2007


Hello! I've been following the development of the D programming language for some time (around 1 year), and I have to say it keeps looking better.

I don't know if these have been proposed before, but I would like to make two suggestions regarding flow control and loops:

1- if behavior on "with" statement:

On the current specification of D, if you want to check if a class can be casted to a subclass, and do something with it, you have to do something like:

if (cast(Foo)bar)
    with(cast(Foo)bar)
    {
        DoSomething();
    }

While that works, it makes you have to write the same thing twice, and unless some compiler optimization kicks in (not sure if compilers check for that), the cast will have to be done twice. (and since it performs a runtime check, it will take some time) You could also use a temporary variable, but that wouldn't be so elegant.

My idea is to make the with statement also behave like an if statement, so the above code could be rewritten as only:

with(cast(Foo)bar)
{
    DoSomething();
}

There's the possibility this would make existing code slower, due to unnecessary checks for null (if you're not typecasting and are sure it's not null), so another possibility would be making the syntax like:

if with(cast(Foo)bar)
{
    DoSomething();
}

So the default "with" behavior would be preserved. Note that since it behaves like an if, you could add an else at the end, like:


if with(cast(Foo)bar)
{
    DoSomething();
} else {
    writeln("Not possible!");
}


2 - for .. finally, while .. finally:

This would allow having something like:

while(someCondition)
{
    DoSomething();
} finally {
    DoOtherThing();
}

The "finally" block would be called at the end of the repetition, only if no "break" was used. This may not seem useful at first, but I think can reduce the number of flags needed to implement various algorithms, making the code faster and more elegant. I'm not sure if this is already possible with scope guards.

That's it.. What do you think?



More information about the Digitalmars-d mailing list