D's greatest mistakes

Andrej Mitrovic andrej.mitrovich at gmail.com
Mon Nov 29 04:21:29 PST 2010


"with" is almost convenient in some cases, but I have to admit every
time I'm inside a with block I'm never absolutely sure which variables
I'm accessing. There's still that situation where I might think I'm
accessing a member variable, but it turns out the member variable
doesn't exist and there just happens to be a local with the same name.
I won't get a warning for that. e.g.:

struct S
{ int r, g; }
void main()
{
    bool b;  // just some state variable..
    // a ton of more code..
    S s;
    with (s)
    {
        writefln("r: %s g: %s b: %s", r, g, b);  // woops, S doesn't
have b but we might get the impression that it does
    }
}

It's tricky to use "with" and be 100% safe.

Here's one older example of using with blocks to create anonymous
objects (Scintilla in this case):
http://pastebin.com/kiXPeQLB

On 11/29/10, bearophile <bearophileHUGS at lycos.com> wrote:
> Manfred_Nowak:
>
>> Daniel Gibson wrote:
>>
>> > What's wrong with "with"?
>>
>> http://www.digitalmars.com/d/archives/digitalmars/D/with_should_be_deprecat
>> ed_with_extreme_prejudice_90375.html#N90375
>
> Andrei said there:
>
>> I think "with" is a very dangerous feature due to the way it hides
>> symbols. It essentially makes the feeblest attempt at modular reasoning
>> utterly impossible:
>>
>> int x, y;
>> with (whatever)
>> {
>>      y += x;
>>      ++x;
>> }
>>
>> What can be said about such code? Nothing. If whatever has or will ever
>> have fields x or y or both, the names will bind to them; otherwise,
>> they'll bind to the locals. Non-local code dependency at its finest.
>
> Today "with" is a bit tricky still, but its main problem that Andrei talks
> about has being patched. So this code:
>
> struct Foo { int x, y; }
> void main() {
>     Foo f;
>     int x, y;
>     with (f) {
>          y += x;
>          ++x;
>     }
> }
>
> Generates:
>
> temp.d(6): Error: with symbol temp.Foo.y is shadowing local symbol
> temp.main.y
> temp.d(6): Error: with symbol temp.Foo.x is shadowing local symbol
> temp.main.x
> temp.d(7): Error: with symbol temp.Foo.x is shadowing local symbol
> temp.main.x
>
> Bye,
> bearophile
>


More information about the Digitalmars-d mailing list