Why should I not use “with” in Delphi?

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

Leave a Comment