Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I not use "with" in Delphi?

Tags:

I've heard many programmers, particularly Delphi programmers scorn the use of 'with'.

I thought it made programs run faster (only one reference to parent object) and that it was easier to read the code if used sensibly (less than a dozen lines of code and no nesting).

Here's an example:

procedure TBitmap32.FillRectS(const ARect: TRect; Value: TColor32); begin   with ARect do FillRectS(Left, Top, Right, Bottom, Value); end; 

I like using with. What's wrong with me?

like image 897
Baldric Avatar asked Sep 16 '08 11:09

Baldric


1 Answers

One annoyance with using with is that the debugger can't handle it. So it makes debugging more difficult.

A bigger problem is that it is less easy to read the code. Especially if the with statement is a bit longer.

procedure TMyForm.ButtonClick(...) begin   with OtherForm do begin     Left := 10;     Top := 20;     CallThisFunction;   end; end; 

Which Form's CallThisFunction will be called? Self (TMyForm) or OtherForm? You can't know without checking if OtherForm has a CallThisFunction method.

And the biggest problem is that you can make bugs easy without even knowing it. What if both TMyForm and OtherForm have a CallThisFunction, but it's private. You might expect/want the OtherForm.CallThisFunction to be called, but it really is not. The compiler would have warned you if you didn't use the with, but now it doesn't.

Using multiple objects in the with multiplies the problems. See http://blog.marcocantu.com/blog/with_harmful.html

like image 200
Lars Truijens Avatar answered Dec 27 '22 03:12

Lars Truijens