Does anyone use 'with' statement?

Bill Baxter dnewsgroup at billbaxter.com
Sat Dec 8 21:34:33 PST 2007


Jarrett Billingsley wrote:
> "serg kovrov" <sergk at mailinator.com> wrote in message 
> news:fjfchm$u14$1 at digitalmars.com...
>> Hi,
>>
>> Recently I have studied a (proprietary language) code. The language 
>> features 'with' statement in the same sense that D does. To understand 
>> what this code sample really do I had to remove all 'with's and 
>> fix/compile code many times before it start working as original.
>>
>> I don't know why never tried to use it in my own code before, but now I 
>> definitely will NOT use it ever. Even if it could save me some typing. I 
>> found 'with' far more evil than even 'goto' (which I don't use as well).
>>
>> -- serg.
> 
> It could probably be overused, but it certainly has its uses.  I don't use 
> it often, but when I do it usually makes for more elegant and less 
> crufty-looking code.  Especially with UI stuff:
> 
> with(myButton = new Button())
> {
>     text = "OK";
>     position = Point(150, 300);
>     size = Size(75, 40);
>     onClick ~= &okHandler;
> }
> 
> Much nicer-looking than the alternatives:
> 
> myButton = new Button();
> myButton.text = "OK";
> myButton.position = Point(150, 300);
> myButton.size = Size(75, 40);
> myButton.onClick ~= &okHandler;
> 
> or:
> 
> myButton = new Button();
> myButton.text("OK")
>     .position(Point(150, 300))
>     .size(Size(75, 40))
>     .onClick ~= &okHandler;
> 
> I'd say using more than one level of a 'with' at a time is probably bad 
> form. 

I agree you need to use it with discipline.  My rules of thumb are to 
only use it when
1) the block of code is short
2) basically every line in the block references the 'with' object, bonus 
points if they're all either LHS or RHS references.
3) the methods being referenced are fairly unambiguous (i.e. not names 
like 'value' which might be defined by lots of different classes)

These are rules of thumb, not hard and fast.  The basic question is 
"will I be able to figure out what this is doing if I come back to this 
code next year".  Which is really what I try to ask myself for all code 
I write, so 'with' isn't really special in that sense.

--bb



More information about the Digitalmars-d mailing list